Search code examples
c#.netsitecoresitecore6

Sitecore Creating Item with Fields[] Included


I want to create an item to sitecore using code behind.

I found this piece of code and it works perfectly fine.

public void CreateItem(String itmName)
{
    //Again we need to handle security
    //In this example we just disable it
    using (new SecurityDisabler())
    {
        //First get the parent item from the master database
        Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
        Item parentItem = masterDb.Items["/sitecore/content/SOHO/Settings/Metadata/Project"];


        //Now we need to get the template from which the item is created
        TemplateItem template = masterDb.GetTemplate("SOHO/Misc/Project");
        //Now we can add the new item as a child to the parent
        parentItem.Add(itmName, template);


        //We can now manipulate the fields and publish as in the previous example
    }
}

But I want to fill in the fields also. like..

Item.Fields["test"].Value="testing";

For that I found out how to edit an item

public void AlterItem()
{
  //Use a security disabler to allow changes
  using (new Sitecore.SecurityModel.SecurityDisabler())
  {
    //You want to alter the item in the master database, so get the item from there
    Database db = Sitecore.Configuration.Factory.GetDatabase("master");
    Item item = db.Items["/sitecore/content/home"];


    //Begin editing
    item.Editing.BeginEdit();
    try
    {
      //perform the editing
      item.Fields["Title"].Value = "This value will be stored";
    }
    finally
    {
      //Close the editing state
      item.Editing.EndEdit();
    }
  }
}

But I have no idea how to combine those 2 things.

I think of 2 methods.

Method 1

Grab the ID of the Item that I created.

I can grab the Name but Name might be duplicated.

Method 2

Fill in the fields before creating the Item

But then.. again I have no idea how to do those 2 methods.

I would be appreciated if I can get some tips.

Thanks in advance.


Solution

  • Method item.Add() returns the created item so your code should look like this:

        Item newItem = parent.Add(itemName, template);
        newItem.Editing.BeginEdit();
        newItem.Fields["fieldName"].Value = "fieldValue";
        newItem.Editing.EndEdit();