Monday, September 22, 2014

Example of Sitecore Command Template With User Interface

Command template define a class and method to be called during an insert operation. Unlike data templates and branch templates, which consist of predefined structures, command templates reference Sitecore UI commands to invoke wizards or other logic used to create new items.


We can create a command template that displays no user interface, a command template that uses a JavaScript prompt to collect an item name, or a command template that displays an ASP.NET or Sitecore Sheer user interface.

We can assign command templates along with data templates and branch templates using insert options.
Following example demonstrates creation of a command template which would check if a folder with current year name exists under main item “News”  and add a “News Item” in that folder. This example uses a JavaScript prompt to collect News Item name.

Step 1: Create two templates “News” & “News Item” with required fields.

Step 2: Create a class that inherits from Sitecore.Shell.Framework.Commands.Command, and override the Execute() method.

namespace Demo.Commands
{
    public class NewsItemCommand : Sitecore.Shell.Framework.Commands.Command
    {
        public override void Execute(Sitecore.Shell.Framework.Commands.CommandContext context)
        {
        }
    }
}

Step 3: Add a /configuration/command element to the file /App_Config/Commands.config.





Step 4: Under the appropriate project-specific folder within /sitecore/Templates, insert a command template definition item using /System/Branches/Command Template data template.






















Step 5: In the command template definition item, in the Data section, for the Command field, enter the command code.


















The parameter id=$ParentID passes the ID of the item under which the user is inserting a new item. Without this parameter, Sitecore would pass the ID of the selected item rather than the item the user right-clicked.

Step 6: Assign this command template to standard values of the “News” template created in step1.




















Step 7: Create a new aspx page in “/sitecore modules/shell”










Step 8: Complete required code in the command class.

public override void Execute(Sitecore.Shell.Framework.Commands.CommandContext context)
        {
            if (context.Items != null && context.Items.Length > 0)
            {
                Item contextItem = context.Items[0];
                NameValueCollection parameters = new NameValueCollection();
                parameters["id"] = contextItem.ID.ToString();
                parameters["name"] = contextItem.Name;
                parameters["database"] = contextItem.Database.Name;
                parameters["language"] = contextItem.Language.ToString();
                Sitecore.Context.ClientPage.Start(this,"Run", parameters);//Run method executes on

            }
        }
        protected void Run(Sitecore.Web.UI.Sheer.ClientPipelineArgs args)
        {
            if (args.IsPostBack)
            {
                if (!(String.IsNullOrEmpty(args.Result)) && (args.Result != "undefined") && (args.Result != "null"))
                {
                }
            }
            else
            {
                Sitecore.Text.UrlString url = new Sitecore.Text.UrlString("/sitecore modules/shell/Demo/News.aspx");
                url.Append("id", args.Parameters["id"]);
                url.Append("database", args.Parameters["database"]);
                Sitecore.Context.ClientPage.ClientResponse.ShowModalDialog(url.ToString(), true);
                args.WaitForPostBack(true);
            }
        }   

Step 9: Handle “OK” and “Cancel” buttons of the user interface News.aspx

protected void btnOK_Click(object sender, EventArgs e)
        {
            if (! String.IsNullOrEmpty(txtNewsItem.Text))
            {
                Sitecore.Data.Database currentDatabase = Sitecore.Configuration.Factory.GetDatabase(Sitecore.Web.WebUtil.GetQueryString("database"));
                Item parentItem = currentDatabase.GetItem(Sitecore.Web.WebUtil.GetQueryString("id"));
                if (parentItem != null)
                {
                    //check if News item contains a folder with current year
                    Item[] children = parentItem.Axes.GetDescendants();
                    Item currentYearItem = children.Where(x => x.TemplateName == "Folder" && x.Name == DateTime.Now.Year.ToString()).SingleOrDefault();
                    if (currentYearItem == null)
                    {
                        Sitecore.Data.Items.TemplateItem folderTemplate = currentDatabase.GetTemplate(Sitecore.TemplateIDs.Folder);
                        if (folderTemplate != null)
                        {
                            Item i = parentItem.Add(DateTime.Now.Year.ToString(), folderTemplate);
                            currentYearItem = i;
                        }
                    }
                    //create a news item and add it to the current folder
                    Sitecore.Data.Items.TemplateItem newsItemTemplate = currentDatabase.GetTemplate(new Sitecore.Data.ID("{D8BE36D8-20F0-4BCF-856C-D069E845D136}"));
                    Item newsItem = currentYearItem.Add(txtNewsItem.Text, newsItemTemplate);
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Close", "window.top.dialogClose();", true);
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Warning", "alert('Please enter news item');", true);
            }
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Close", "window.top.dialogClose();", true);
        }

Step 10: Create a main news item based on “News” template.

Step 11: Create a news item under main item by clicking the command template which would create a folder with current year and a “News Item” under that folder.











































Thursday, September 18, 2014

Example of Sitecore Command Template Using Java Script:

Command template define a class and method to be called during an insert operation. Unlike data templates and branch templates, which consist of predefined structures, command templates reference Sitecore UI commands to invoke wizards or other logic used to create new items.

We can create a command template that displays no user interface, a command template that uses a JavaScript prompt to collect an item name, or a command template that displays an ASP.NET or Sitecore Sheer user interface.

We can assign command templates along with data templates and branch templates using insert options.

Following example demonstrates creation of a command template which would check if a folder with current year name exists under main item “News”  and add a “News Item” in that folder. This example uses a JavaScript prompt to collect News Item name.

Step 1: Create two templates “News” & “News Item” with required fields.

Step 2: Create a class that inherits from Sitecore.Shell.Framework.Commands.Command, and override the Execute() method.

namespace Demo.Commands
{
    public class NewsItemCommand : Sitecore.Shell.Framework.Commands.Command
    {
        public override void Execute(Sitecore.Shell.Framework.Commands.CommandContext context)
        {
        }
    }

}

Step 3: Add a /configuration/command element to the file /App_Config/Commands.config.







Step 4: Under the appropriate project-specific folder within /sitecore/Templates, insert a command template definition item using /System/Branches/Command Template data template.























Step 5: In the command template definition item, in the Data section, for the Command field, enter the command code.


















The parameter id=$ParentID passes the ID of the item under which the user is inserting a new item. Without this parameter, Sitecore would pass the ID of the selected item rather than the item the user right-clicked.

Step 6: Assign this command template to standard values of the “News” template created in step1.




















Step 7: Complete required code in the command class.

  public override void Execute(Sitecore.Shell.Framework.Commands.CommandContext context)
        {
            if (context.Items != null && context.Items.Length > 0)
            {
                Item contextItem = context.Items[0];
                NameValueCollection parameters = new NameValueCollection();
                parameters["id"] = contextItem.ID.ToString();
                parameters["name"] = contextItem.Name;
                parameters["database"] = contextItem.Database.Name;
                parameters["language"] = contextItem.Language.ToString();
                Sitecore.Context.ClientPage.Start(this,"Run", parameters);// Executes custom method with required task
            }
        }
        protected void Run(Sitecore.Web.UI.Sheer.ClientPipelineArgs args)
        {
            if (args.IsPostBack)
            {
                if (!(String.IsNullOrEmpty(args.Result)) && (args.Result != "undefined") && (args.Result != "null"))
                {
                    Sitecore.Data.Database currentDatabase = Sitecore.Configuration.Factory.GetDatabase(args.Parameters["database"]);
                    Item parentItem = currentDatabase.GetItem(args.Parameters["id"]);
                    if (parentItem != null)
                    {
                        //check if News item contains a folder with current year
                        Item[] children = parentItem.Axes.GetDescendants();
                        Item currentYearItem = children.Where(x => x.TemplateName == "Folder" && x.Name == DateTime.Now.Year.ToString()).SingleOrDefault();
                        if (currentYearItem == null)
                        {                         
                            Sitecore.Data.Items.TemplateItem folderTemplate = currentDatabase.GetTemplate(Sitecore.TemplateIDs.Folder);
                            if (folderTemplate != null)
                            {
                                Item i = parentItem.Add(DateTime.Now.Year.ToString(), folderTemplate);
                                currentYearItem = i;
                            }
                        }
                        //create a news item and add it to the current folder
                        Sitecore.Data.Items.TemplateItem newsItemTemplate = currentDatabase.GetTemplate(new Sitecore.Data.ID("{D8BE36D8-20F0-4BCF-856C-D069E845D136}"));
                        Item newsItem = currentYearItem.Add(args.Result, newsItemTemplate);
                    }
                }
            }
            else
            {
                //Java script prompt to get the news item name to be created
                Sitecore.Context.ClientPage.ClientResponse.Input("Enter News Item Name", Sitecore.Globalization.Translate.Text("Name"), Sitecore.Configuration.Settings.ItemNameValidation, "'$Input' is not a valid name.", 10);
                args.WaitForPostBack();
            }
        }    

Step 8: Create a main news item based on “News” template.

Step 9: Create a news item under main item by clicking the command template which would create a folder with current year and a “News Item” under that folder.






















Wednesday, September 17, 2014

Sitecore Branch Template Example

A Template defines the fields and sections associated with a type of item. Items in sitecore can be created using three different template types.

·         Data Template:  form the framework around which items are built. They define fields used to control how data is entered and can inherit from other templates to enable reuse.

·         Branch Template: allow you to create a set of items rather than a single item at a time.

·         Command Template: allow insert of items according to logic rather than predefined structures.

Data Template: A data template defines a data type. Sitecore associates a data template with each item. The data template defines the structure of all items associated with that data template. A data template contains a number of data template sections, each of which contains a number of data template fields.

Branch Template: A branch template consists of a branch template definition item, which can contain a single item, a hierarchy of items, or multiple hierarchies of items. When a user invokes a branch template, Sitecore duplicates the item(s) beneath the branch template definition item, including any field values, and then performs token substitution on item names and field values.

Following tokens can be used in field values of each of the items inserted using branch template.

Token
Value
$name
The name entered by the user when inserting the item
$id
The ID of the item
$parentid
The ID of the parent of the item
$parentname
The name of the parent of the item
$date
The system date (yyyyMMdd)
$time
The system time (HHmmss)
$now
The date and time (yyyyMMddTHHmmss)


Following example creates a branch template, which can be used to create a “Shopping” item with two folders “Brands” and “Products” and each folder with a respective sample item.
















Step 1: Create three templates “Shopping”, “Brand” & “Product” with “Title” & “Description” fields











Step 2: Create a new Branch. Navigate to “sitecore/templates/Branches” , right click and insert “ New Branch”




Step 3: Select “Shopping” template in the “Create a New Branch” branch template wizard


























Step 4: Right click on $name and create two new folders “Brands” & “Products”


























Step 5: Right click on “Brands” folder and create a sample item using “Brands” template. Then create a sample item using “Products” template under “products” folder.

















Step 6: Right click on Home and create a content item from the new branch template.


Monday, September 15, 2014

Creating An Editable Sitecore Page With Glass Mapper

Before working on this example,  Click Here to view basic sitecore page creation using Glass Mapper which would be modified to create an editable page.

Following steps are required to make an Editable page

 Step 1: Add an additional property to the DemoPage model, to represent the Sitecore ID. The property that represents the Sitecore ID is required to allow Glass.Mapper to link your model to the actual Sitecore item in Page Edit mode.

using Glass.Mapper.Sc.Configuration.Attributes;
namespace Glass.Mapper.Models.Demo
{
    [SitecoreType]
    public class DemoPage
    {
        [SitecoreId]
        public virtual Guid Id { get; set; }
        [SitecoreField("Page Title")]
        public virtual string PageTitle { get; set; }
        [SitecoreField("Page Description")]
        public virtual string PageDescription { get; set; }
    }

}

Step 2: Create a Sublayout which is inherited from the GlassUserControl. This control is generic and takes the type that you want to be loaded. The GlassUserControl already has a property called Model and also has some useful methods to make fields editable.

using Glass.Mapper.Sc;
using Glass.Mapper.Sc.Web.Ui;
using Glass.Mapper.Models.Demo;
public partial class layouts_PageData : GlassUserControl<DemoPage>
{
     protected void Page_Load(object sender, EventArgs e)
    {
    }

}

Step 3: Make ASCX editable

<h1><%= Editable(x => x.PageTitle) %></h1><br />
<%= Editable(x => x.PageDescription) %>

Friday, September 12, 2014

Creating A Sitecore Page With ORM Tool ( Glass Mapper)

Glass Mapper is an object mapping framework (ORM tool) for mapping Sitecore items directly onto an object model allowing you to model your entire Sitecore solution as a data model. The framework handles converting data to and from fields and pulling data from related items. It also helps in making Sitecore code unit testable.

Below example uses CastleWindsor dependency injection framework.


Step 1: Install Glass.Mapper.Sc.CastleWindsor from NuGet packages


Step 2: Create two base templates “Page Title” and “Page Description” 











Step 3: Create a page inheriting from two templates














Step 4: Insert standard values by selecting “Builder” tab of data template and clicking on “Options” in the main menu.

















Step 5: Create a layout and put necessary place holders.



















In DemoLayout.aspx

<div id="MainPanel">

      <sc:placeholder key="main" runat="server" />

   </div>

Placeholder is an area of the page to support the user adding controls. Placeholders can be placed on layouts, sublayouts and view renderings.

Step 6: Create a sub layout


Step 7: Create a Model based on the data template

using System;
using System.Web;
using Glass.Mapper.Sc.Configuration.Attributes;

namespace Glass.Mapper.Models.Demo
{

    public class DemoPage
    {

        [SitecoreField("Page Title")]
        public virtual string PageTitle { get; set; }
        [SitecoreField("Page Description")]
        public virtual string PageDescription { get; set; }

    }

}

Step 8: Load model of the current item using SitecoreContext

using Glass.Mapper.Sc;
using Glass.Mapper.Models.Demo;

public partial class layouts_PageData : System.Web.UI.UserControl
{

    public DemoPage Model { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {

        var context = new SitecoreContext();
        Model = context.GetCurrentItem<DemoPage>();

    }

}

Step 9: Render data from model on to the ascx page.

<h1><%= Model.PageTitle%></h1><br />
<%= Model.PageDescription %>

Step 10: Create a place holder setting item and allow above sublayout. Placeholder settings provide all of the details for the placeholder to Page Editor including the controls that can be added.



















Step 11: Assign layout, sub layout and placeholder settings to the template.

To set layout, go to standard values, click on edit and set the layout













Click on controls and set the sub layout


























Set the placeholder setting



























Step 12: Set Insert Options for the home item template to “Page” template.


















Create a page based on the template.