Monday, September 29, 2014

Sitecore Proxies And Clones

A)  Proxies:

Proxy items duplicate’s an item (or sub tree) from one part of the content tree to another. Any Update to proxy item will update the source item and vice versa.


Proxies are generally used when we need an item appear as a child item to multiple parent items. Following example demonstrates a book item appearing under multiple genre items.























Step 1: Set proxiesEnabled element to true in web.config at /configuration/sitecore/databases for master and web databases.

<databases> 
<database id="master" singleInstance="true" type="Sitecore.Data.Database, Sitecore.Kernel">    
<proxiesEnabled>true</proxiesEnabled>   
</database>
</databases>

Step 2: Create two new templates “BookCategory” & “Book” with “Title” & “Description” fields.


















Step 3: Create book items from book template in a common folder.


















Step 4: Create “Comedy”, “Fiction” & “Romance” categories from “BookCategory” template.





























Step 5: Create proxy items at /Sitecore/System/Proxies location using /System/Proxy data template.


Step 6: Set the source item and target item of proxy. Here, “Book1” is the source item and “Comedy” is the target item.






















Step 7: Create other proxies as required.





















Step 8: Editing any proxy item would affect source item and vice versa

Publishing a proxy
<publishVirtualItems> setting in web.config indicates whether Sitecore should publish virtual items as if they were normal items.
If this setting is set to true, virtual item becomes a real item and the relationship between virtual item and parent item no longer exist.
If this setting is set to false (preferred), relationship between virtual item and parent item exist even on web database if proxies are enabled on the web database.

B)  CLONES

Cloning creates a dynamic duplicate of an item or branch in the content tree to another different location within the same content tree. A clone inherits field values from the parent item instead of standard values and provides notification to clone item whenever parent item is modified.

If all fields of parent item and cloned item are same, then any change to parent item would apply changes to all cloned items immediately without any prompt.

If the value in the cloned item is different to parent item, Sitecore creates a notification, which the user must accept in order to apply the change to the cloned item.

Cloned items when published, become real items and the relationship between cloned item and parent item no loner exist.

Following steps show an example of creating a clone

Step 1: Select the parent item to be duplicated and click on “Clone” button in the “Configure” section.




















Step 2: Select the destination for the cloned item and click on “Clone” button.




















Step 3: Changing field value in the cloned item will not affect the parent item.










































Step 4: Change parent item field value. Since content of parent and cloned item are different, sitecore creates a notification which user must accept.























UNCLONE: A clone can be converted to a normal item, severing any ties it has to the original and become completely independent by uncloning.


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.