Create items programmatically based on template in sitecore

How do you insert an item into Sitecore programmatically based on the template?

Sitecore is famous because of it provides a lot of Apis from which you can create, edit, and delete items in the content tree.Creating a new item using the template is very simple using the Sitecore API.

Follow the below steps to Create items programmatically based on template in Sitecore.

1. Use the Security Disabler to disable the security. Not necessary to login into the Sitecore.
2. Get the Master Database using Sitecore.Data.Database.GetDatabase("master")
3. Get the template type using Item.TemplateItem API for which you need to create the item.
4. Get the Item path where you need to insert the new item. This is the parent item path of the new item.
5. Add the new item to the parent item path.
6. Update the Fields of a new item created using the Item.Editing.BeginEdit() and Item.Editing.EndEdit()

Sample Code to Create items programmatically based on template in Sitecore

// The SecurityDisabler is required which will overrides the current security model, allowing the code
// to access the item without any security. 
using (new Sitecore.SecurityModel.SecurityDisabler())
{
  // Get the master database
  Sitecore.Data.Database master = Sitecore.Data.Database.GetDatabase("master");
  // Get the template for which you need to create item
  Items.TemplateItem template = master.GetItem("/sitecore/templates/Sample/Sample Item");
 
  // Get the place in the site tree where the new item must be inserted
  Item parentItem = master.GetItem("/sitecore/content/home");
 
  // Add the item to the site tree
  Item newItem = parentItem.Add("NameOfNewItem", template);
 
  // Set the new item in editing mode
  // Fields can only be updated when in editing mode
  // (It's like the begin transaction on a database)
  newItem.Editing.BeginEdit();
  try
  {
  // Assign values to the fields of the new item
  newItem.Fields["Title"].Value = "NewValue1";
  newItem.Fields["Text"].Value = "NewValue2";
 
  // End editing will write the new values back to the Sitecore
  // database (It's like commit transaction of a database)
  newItem.Editing.EndEdit();
  }
  catch (System.Exception ex)
  {
  // Log the message on any failure to sitecore log
  Sitecore.Diagnostics.Log.Error("Could not update item " + newItem.Paths.FullPath + ": " + ex.Message, this);
 
  // Cancel the edit (not really needed, as Sitecore automatically aborts
  // the transaction on exceptions, but it wont hurt your code)
  newItem.Editing.CancelEdit();
  }
}

Check out the article Publish items in Sitecore programmatically using API to know how to publish the items in Sitecore using the code.

Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like