How to create items programmatically in Sitecore

Qwerty picture Qwerty · Mar 3, 2016 · Viewed 10.7k times · Source

In the content tree, the structure is as follows

Home
 -England
 -France
 -Germany

There is a sublayout (CommentsForm.ascx), which is used in all the 3 pages. When user browses 'France' and submits a comment, the 'Comment' item should get saved under 'France' and so on..

In this scenario, the Parent item (under which the new item has to be created), is dynamic. So, how to get the parent item in such case. Is this correct?

protected void btnSubmit_Click(object sender, EventArgs e)
{
 Sitecore.Data.Database masterDB =   Sitecore.Configuration.Factory.GetDatabase("master");

 Item parentItem = Sitecore.Context.Item;

 string name = "Comment_" + Sitecore.DateUtil.IsoNow;
 TemplateItem template = masterDb.GetTemplate("/sitecore/templates/userdefined/Comment");     

 using (new SecurityDisabler())
 {
   //how to go about here??
   //newItem["Author"] = txtAuthor.text;
   //newItem["CommentText"] = txtComments.Text;
   //parentItem.Add("name", template);
 }
}

Answer

Vlad Iobagiu picture Vlad Iobagiu · Mar 3, 2016

You can use UserSwitcher safer in production, but you can also use SecurityDisabler using(newSecurityDisabler()){}

Editing and renaming must happen in an Editing.BeginEdit() transaction

 Sitecore.Data.Database masterDB =   Sitecore.Configuration.Factory.GetDatabase("master");

 Item parentItem = Sitecore.Context.Item;

 string name = "Comment_" + Sitecore.DateUtil.IsoNow;
 var template = masterDb.GetTemplate("/sitecore/templates/userdefined/Comment");     

using (new Sitecore.SecurityModel.SecurityDisabler())
{
try
{
  Item newItem = parentItem.Add("Name", template);
  if (newItem!=null)
  {
    newItem.Editing.BeginEdit();
   newItem["Author"] = txtAuthor.text;
   newItem["CommentText"] = txtComments.Text;
   newItem.Editing.EndEdit();
  }
}
catch
    {
      newItem.Editing.CancelEdit();
    }
 }