Saturday, 29 August 2015

Sitecore Items Operations


In the last project I worked on I face a number of cases in which I needed to use sitecore API for different operations and I believe it will be useful to share the following operations:

1.       Add/Edit sitecore item ( different language versions )
2.       Delete/Recycle sitecore item
3.       Set sitecore Item workflow.
4.       Publish Sitecore Item ( Allow/Prevent publish).
5.       Read Item security access rights.
6.       Set sitecore item sort order.



1.       Add/Edit sitecore item ( different language versions )
Let's start with adding sitecore item with editing item fields with specific language, To add new sitecore item you need to know the parent of the new item and the template which will be the type of the new item, as you can see in the following code a sitecore item will be created and its field will be filled using the language switcher value "en" , and if you need you need to create a new language version of this item you just go the language switcher block and create new method and update the language switcher value with "fr" as example to create a French version of this item.
 

public void CreateItem(Item ParentItem,ID TemplateId,string ItemName)
{
try
{
using (new Sitecore.Globalization.LanguageSwitcher("en"))
{
using (new SecurityDisabler())
{
// get the parent item from the master database
Sitecore.Data.Database masterDb = GetMasterDB();
ItemName = ItemUtil.ProposeValidItemName(ItemName);
//get the template from which the item will be created
TemplateItem template = masterDb.GetTemplate(TemplateId);
//add the new item as a child to the parent
Sitecore.Data.Items.Item item = ParentItem.Add(ItemName, template);
if (item != null)
{
//Begin editing
item.Fields.ReadAll();
item.Editing.BeginEdit();
//perform the editing
// Update Item fields values
item.Fields["Field1Name"].Value = "Field1 Value";
item.Fields["Field2Name"].Value = "Field2 Value";
item.Fields["Field3Name"].Value = "Field3 Value";
item.Editing.EndEdit();
}
}
}
}
catch (Exception exception)
{
throw exception;
}
}
view raw CreateItem.cs hosted with ❤ by GitHub




2.       Delete/Recycle sitecore item

You need to know that when you delete a sitecore item then you can't restore that item again but if you recycle the item then the item will be restored using sitecore recycle bin but you should enable  the recycle bin feature using the web.config setting see below:

<!--  RECYCLE BIN
            If true, when deleting items in the client, they will
            be moved to the recycle bin rather than being deleted
            Default value: true
-->
<setting name="RecycleBinActive" value="true"/>


The following will show how to delete a sitecore item:


public void DeleteItem(Item ItemToDelete)
{
try
{
ItemToDelete.Delete();
}
catch (Exception ex)
{
throw ex;
}
}
view raw DeleteItem.cs hosted with ❤ by GitHub

And the following will show how to recycle a sitecore item:

public void RecycleItem(Item ItemToRecycle)
{
try
{
ItemToRecycle.Recycle();
}
catch (Exception ex)
{
throw ex;
}
}
view raw RecycleItem.cs hosted with ❤ by GitHub


3.       Set Sitecore Item Workflow

Let's suppose that you need to set the state of workflow of a sitecore item to the final workflow, check the following code:

public void PushItemToFinalWorkflowState(Item item)
{
Database masterDb = Factory.GetDatabase("master");
using (new Sitecore.Globalization.LanguageSwitcher("en"))
{
//Use a security disabler to allow changes
using (new Sitecore.SecurityModel.SecurityDisabler())
{
item = masterDb.GetItem(item.ID);
item.Editing.BeginEdit();
IWorkflow _existingWF = masterDb.WorkflowProvider.GetWorkflow(item);
if (_existingWF != null)
{
WorkflowState _workflowState = _existingWF.GetStates().FirstOrDefault(P => P.FinalState);
item.Fields[Sitecore.FieldIDs.WorkflowState].Value = _workflowState.StateID;
}
item.Editing.EndEdit();
}
}
}
view raw ItemWorkflow.cs hosted with ❤ by GitHub






4.       Publish Sitecore Item( Allow/Prevent publish).

The following code will show how you can publish item from master database to web database:

public static void PublishItem(ID ItemId)
{
try
{
using (new Sitecore.SecurityModel.SecurityDisabler())
{
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Database target = Sitecore.Configuration.Factory.GetDatabase("web");
Sitecore.Data.Items.Item home = master.GetItem(ItemId);
Sitecore.Data.Database[] targetDatabases = { target };
Sitecore.Globalization.Language[] languages = master.Languages;
bool deep = true;
bool compareRevisions = false;
Sitecore.Publishing.PublishManager.PublishItem(home, targetDatabases, languages, deep, compareRevisions);
}
}
catch (Exception ex)
{
throw ex;
}
}
view raw PublishItem.cs hosted with ❤ by GitHub

To prevent item publish all what you need to is update operation as I explained in the first point to update the sitecore item system field "__Never publish" with a value "1" and  that item will not be published, you can also do this using the sitecore content editor.

5.       Read Item Security Access Rights

In some cases you need to read and list all the security item rights for an item and to do this check the following code:

public void ReadItemAccessRules(Item item)
{
var accessRules = item.Security.GetAccessRules();
if (accessRules != null)
{
foreach (var rule in accessRules)
{
string temp += " - " + rule.Account.Name + " = " + rule.AccessRight.Name + " = " + rule.SecurityPermission + "\n" ;
}
}
}

6.       Set Sitecore Item Sort Order

Sometimes you need to set the sort order for some items under spacific parent, and to do that you just need an update operation like the one described in point number one above to update the sitecore system field " __sortorder" for the required item and the value would be 100, 200 ,300 ....

I hope the above will help.

1 comment:

Unknown said...

Great Site, The Course were so simple and easy to understand.
Sitecore Online Training

Post a Comment