Sitecore : Programmatically add and publish Sitecore items through Workflow

In this post, I will show how to auto publish an Item in Sitecore. This is handy as sometimes you have to create items from external XML feeds or databases.

The code snippet also includes adding item to workflow and auto executing it to the final stage

Steps to follow

1. We need to switch from the current site context to shell (if your code is running from within the site)
2. Then use SecurityDisabler() to switch into admin mode
3. Get the master database
4. Get the template
5. Get the path where Item has to be placed
6. Check if the item path does not exists, if it doesnt then create a new item
7. Create and Edit your item
8. Move to workflow (if required)
9. Do an incremental publish

Here is the code snippet (some values are hard coded, but again you can get them from config/settings)

//step 1-Switch context
string currentSiteName = Sitecore.Context.Site.Name;
Sitecore.Context.SetActiveSite("shell");
//step 2-Switch to admin mode
using (new Sitecore.SecurityModel.SecurityDisabler())
{
//step 3-Get master database
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");

Item newItem = null;
//step 4 - Get data template
TemplateItem templateItem = master.GetTemplate("User Defined/My Template");
//step 5 - Define static path
string path = "/sitecore/content/Home/My Template Items/";
//myItemPath might change with in a for loop or by passing variables
string myItemPath = "My new Item";
//define complete path
myItemPath = path + myItemPath
//step 6 - check if it exists
if (master.GetItem(myItemPath ) == null)
{
//step 7 - create and edit
newItem = master.CreateItemPath(myItemPath, templateItem);
newItem.Editing.BeginEdit();
newItem.Fields["Title"].Value = "My Item Title"; //programattically update the field
//amend more fields if required
newItem.Editing.EndEdit();
newItem.Editing.AcceptChagnes();

//step 8 - add to workflow if requried and place it in start state and then execute the final stage
Sitecore.Workflows.IWorkflow workflow = master.WorkflowProvider.GetWorkflow(newItem);
workflow.Start(newItem);
workflow.Execute(Config.AutoPublishCommandID, newItem, "auto approved", false);

//step 9 - publish to pre-defined targets and langugaes
Database[] targetDBs = new Database[] { Sitecore.Configuration.Factory.GetDatabase("web") };
Language[] languages = new Language[] { LanguageManager.GetLanguage("en") };
Sitecore.Publishing.PublishManager.PublishIncremental(master, targetDBs, languages);


}

}

//switch back to current site
Sitecore.Context.SetActiveSite(currentSiteName);

Cheers

One thought on “Sitecore : Programmatically add and publish Sitecore items through Workflow

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.