Basics of Templates Creation in Sitecore

In general, templates basically should be defined under below categories at least. Templates are the most basic thing which is defined at the initial stage in Sitecore.

In general, templates basically should be defined under below categories at least.

  • Base templates
  • Data templates
  • Rendering parameter templates
  • Site configuration or settings templates
  • Page templates

Base templates as the name signifies that it should consists of the fields which is likely to be the part of most of the templates. For example- Title, Image and description and link fields. These fields can be part of many templates so instead of duplicating the same fields in all templates create it as a base template and inherit it.

Data templates are basically the Entities in the system. As we define entities in our code same way you can create Data templates and its fields. For example Product template in a ecommerce application.

Rendering parameter templates should be defined in a different folder and with rendering name as prefix so that one can get information of all the renderings for which rendering parameters exist.

Site configuration templates should be created in order to configure settings for Site specific data which is common on all pages. For example: enabling or disabling Banner and popups on the Site pages.

Page templates are the templates which might be inheriting data templates. Basically, these are the templates which will contain presentation (means renderings, placeholder and layouts) and are created based on number of website unique pages. For example: Page template might inherit Data templates, meta data templates.

Get single Item or multiple items in Sitecore based on different scenarios.

Get Item by ID:

Everything is an Item in sitecore and every item has an ID and Path.

If the return type of any method is Sitecore Item then we get all the properties and methods related to Item class.

Sitecore.Data.Database db = Sitecore.Configuration.Factory.GetDatabase(“master”);

string itmID={726C1CEB-46BC-483E-AAB4-44205C60773D}”);//Id of a sitecore Item
Item itmbyID=databas.GetItem(itmID);

Get Item by Path:

string itmPath=”/sitecore/content/home/ItemA”;

Item itmbyPath=databas.GetItem(itmPath);

Note: we should always try to get a item in sitecore by its Id not by its Path because path of any item can change by someone or accidentally(during Item move) but its item ID remains same.

Get Item using Sitecore query

Item item = Sitecore.Context.Database.SelectSingleItem("/sitecore/content/Site Data/Email Configuration");

Get Multiple Items using sitecore query

Item[] items = Sitecore.Context.Database.SelectItems("/sitecore/content/Site Data/Products//*[@@templateid='{B0707AB3-64C9-4CA1-AED4-3A1201208295}' ]");

Get multiple Items using Sitecore Fast query

Item[] items = Sitecore.Context.Database.SelectItems("fast://sitecore/content/Site Data/Products//*[@@templateid='{B0707AB3-64C9-4CA1-AED4-3A1201208295}']");

 Get all the descendants of the item using Sitecore API

Item item = Factory.GetDatabase(“web”).GetItem(“/sitecore/content/Site Data/Products”);
Item[] items=item.Axes.GetDescendants()

This method calls item.Children, and then for each child again child.Children recursively. And it adds all those items to an array.

There is another method which takes query as input as mentioned below:

item.Axes.Selectitems(string query) 

This method executes Sitecore query passed in the argument in the context of the current item

Get Descendents always fetch the child items recursively. It should be used carefully as it has huge performance hit if child items are large in size

Difference in UserSwitcher and SecurityDisabler

When we decide to create,update or delete items in sitecore programmatically we need to run our code in either Securitydisabler context or UserSwitcher context.

when we want to run the code in context of another user we should use Sitecore.Security.Accounts.UserSwitcher class for example there are scenarios in which only user A is allowed to create,update or delete items under a particular node in the tree and you want the code to fail if someone else tries to do the changes.

string userA = @”sitecore\userA”;
Sitecore.Security.Accounts.User sitecorecuser =Sitecore.Security.Accounts.User.FromName(userA, false);
using (new Sitecore.Security.Accounts.UserSwitcher(sitecorecuser))
{
//your code goes here
}

when we want to run the code without any security restrictions then we should use Sitecore.SecurityModel.SecurityDisabler class. Basically SecurityDisabler elevates the users permission (temporarily) to admin rights and so context user will be able to perform anything in sitecore. Any changes done with the SecurityDisabler will show up as being done by the sitecore\Anonymous role.

using (new Sitecore.SecurityModel.SecurityDisabler())
{
  //your goes code here
}


Adding, Updating and deleting items in Sitecore Programmatically

Apart of manually creating, updating and deleting Sitecore items and its fields content we can also do the same activity programmatically. This helps when we need to create Sitecore content quickly from a excel sheet, csv or external database.

First, we will see how we can create an item by code.

Create Item in Sitecore

//Get the database reference where the item will be created.

Database msDB = Sitecore.Configuration.Factory.GetDatabase(“master”);

Or context DB

Database msDB = Sitecore.Context.Database;

//Get the content node or parent node where to create the item

Item parentItm = masterDb.Items[“/sitecore/content/home”];

//get the schema of the item, template on which item will be created

TemplateItem templateItm = msDB.GetTemplate(“sample/sample item”);

//Add it to the content tree

parentItm.Add(“ItemName”, templateItm);

This code should be enclosed inside below using statement.

 Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.FromName(@”sitecore\User001″, false);

        using (new Sitecore.Security.Accounts.UserSwitcher(User001))

        {            // code goes here        }

Here User001 account should be setup correctly so that he has the necessary access rights to add the items in sitecore.You can use SecurityDisabler also but there is a difference when we should use UserSwitcher vs SecurityDisabler .See my next post https://techcmsblogsrohit.com/difference-in-userswitcher-and-securitydisabler/