This post is dedicated to the newborn Sitecore developers. Generally, the newborn Sitecore developers stuck in a situation when they need to create a new Sitecore item or modify the existing or new item programmatically.
This post will take them to their destination where they will find a piece of code which will help them in achieving their goal of creating/modifying Sitecore items programmatically.
Creating item programmatically
This below code will explain you the process of creating an item dynamically
//Disable the Security using (new SecurityDisabler()) { //First get the desired DB where you want to create the item Database master = Sitecore.Configuration.Factory.GetDatabase("master"); if (master != null) { //Here you need the Parent Item (new item will be child of this item) Item parentItem = master.GetItem(new ID("{4F67FC21-199E-414C-BE96-E861281F1413}")); //Get the template for the new item TemplateItem template = master.GetTemplate(new ID("{E5934ED6-8D4F-4FEB-AA1A-AA06C783195F}")); if (template != null) { //Now, use Parent item to add a new item underneath and pass the item name and template as parameter Item newItem = parentItem?.Add("NewItem", template); } } }
Modifying the Item content programmatically
the below code will help you understand the item alteration dynamically
//again disable the security using (new SecurityDisabler()) { //get the item to modify the content //Get the DB to get the Item Database master = Sitecore.Configuration.Factory.GetDatabase("master"); //get the Item from the DB to modify the content var item = master.getItem(new ID("{4F67FC21-199E-414C-BE96-E861281F1413}")); //Enter into the item editing state item.Editing.BeginEdit(); //Now you can edit the item field values as belwo item["title"] = "some value" //once you are done with the editing, come out of editing satate then item.Editing.EndEdit(); }
So that’s the very basic of Sitecore API where you could create/modify the items dynamically from your C# code.
Happy Coding!!!