Place an item in editing mode

Version: 10.4

Sitecore APIs that update items may throw exceptions if the item is not in editing mode. You can place an item in editing mode by using methods of the Sitecore.Data.Items.Item.Editing property, or by using the Sitecore.Data.Items.EditContext class.

Note

Be aware that a CD server does not have access to the master database, so if you wrote something public-facing that edits an item (which you never do), it wouldn’t work in a production environment.

For example, the following code places the /Sitecore/Content/Home item in the Master database in editing mode within a security disabler using methods in the Sitecore.Data.Items.Item.Editing class:

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

Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");

using (new Sitecore.SecurityModel.SecurityDisabler())
{
    home.Editing.BeginEdit();

    try
    {
        // Edit item
        home.Editing.EndEdit();
    }
    catch (Exception ex)
    {
        home.Editing.CancelEdit();
    }
}

If you do call the Sitecore.Data.Items.Item.Editing.CancelEdit() method or do not call the Sitecore.Data.Items.Item.Editing.EndEdit() method, Sitecore does not commit the changes.

Important

Developers should use try/catch blocks as shown in this example. For brevity, code examples in this document do not always include try/catch blocks.

Alternatively, you can use the Sitecore.Data.Items.EditContext class with a C# using a statement to place an item in editing mode. The closure of the using statement invokes the Sitecore.Data.Items.EditContext.Dispose() method, which commits any changes made within that segment of code.

For example, the following code places the /Sitecore/Content/Home item in the Master database in editing mode using a Sitecore.Data.Items.EditContext:

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

Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");

//TODO: eliminate SecurityDisabler if possible

using (new Sitecore.SecurityModel.SecurityDisabler())
{
    using (new Sitecore.Data.Items.EditContext(home))
    {
        // Process home
    }
}
Note

If you use the Sitecore.Data.Items.EditContext class, you cannot explicitly rollback changes. If code within the using statement throws an exception, the closing of the using statement automatically commits any changes made before the exception.

Do you have some feedback for us?

If you have suggestions for improving this article,