How to assign templates to another template dynamically in sitecore?

岁酱吖の 提交于 2019-12-25 16:54:04

问题


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

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");

回答1:


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



来源:https://stackoverflow.com/questions/21060665/how-to-assign-templates-to-another-template-dynamically-in-sitecore

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!