Skip to content

Instantly share code, notes, and snippets.

@DaveGoosem
Created June 20, 2013 00:31
Show Gist options
  • Save DaveGoosem/5819372 to your computer and use it in GitHub Desktop.
Save DaveGoosem/5819372 to your computer and use it in GitHub Desktop.
// The SecurityDisabler overrides the current security model, allowing you
// to access the item without any security. It's like the user being an administrator
using (new Sitecore.SecurityModel.SecurityDisabler())
{
// Get the master database
Sitecore.Data.Database master = Sitecore.Data.Database.GetDatabase("master");
// Get the template to base the new item on
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 tarnsaction on a database)
newItem.Editing.BeginEdit();
try
{
// Assign values to the fields of the new item
newItem.Fields["Title"].Value = "Value1";
newItem.Fields["Text"].Value = "Value2";
// 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)
{
// The update failed, write a message to the 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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment