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;
//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.Fields["Title"].Value = "My Item Title"; //programattically update the field
//amend more fields if required

//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.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



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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s