Wiki
Wiki

Reputation: 102

How to assign templates to another template dynamically in sitecore?

I know how to add or create Item programmatically. My doubt is how to assign the template as below programmatically?

enter image description here

Sitecore.Data.Database masterDatabase = Sitecore.Configuration.Factory.GetDatabase("master");
//This is master item.I want to add  some items in this template.like below programatically
Item MasterItem = masterDatabase.GetItem("/sitecore/templates/DynamicTemplates/Employees");

//This is folder which has two templates[Developers,Tester].I want to assign these two as in image programatically.
Item GetAllTemplates = masterDatabase.GetItem("/sitecore/templates/DynamicTemplates/Team");

Upvotes: 0

Views: 1018

Answers (1)

Martin Davies
Martin Davies

Reputation: 4456

This seems like quite a strange request and I would suggest that you reconsider because taking approach will cause you problems eventually.

Having said that, Templates are items like everything else in Sitecore so it should be possible. Once you have the MasterItem instantiated you should be able to add things to its __Base template field.

__Base template is a Multlist field, so the value is stored as a string of pipe separated GUIDs.

Using your variables:

var baseTemplates = GetAllTemplates.Children;
var baseTemplateIds = baseTemplates.Select(item => item.ID.ToString());
var fieldValue = String.Join("|",baseTemplateIds);

using (new Sitecore.SecurityModel.SecurityDisabler())
{
    try
    {
        MasterItem.Editing.BeginEdit();
        MasterItem["__Base template"] = fieldValue;
    }
    finally
    {   
        MasterItem.Editing.EndEdit();
    }
}

if you're new to editing items programatically, take a look here:

http://learnsitecore.cmsuniverse.net/en/Developers/Articles/2009/06/ProgramaticallyItems2.aspx

Upvotes: 2

Related Questions