Sitecore通过模板添加字段时如何指定数据字段类型.AddField(字符串,字符串);



如果我有一个Sitecore项目item,我添加一个数据字段"My field "给它使用:

 item.Template.AddField("My Field", "Data");

如何为它指定字段类型?例:Single-Line Text

AddField(...)方法返回添加的模板字段(它还没有类型)。

你可以这样设置模板字段的类型:

var templateField = item.Template.AddField("Field name", "Section name");
using (new EditContext(templateField.InnerItem)) {
    templateField.Type = "Single-Line Text";
}

类型值应与字段类型的名称相对应,如Single-Line TextRich TextGrouped Droplist

根据您的安全性,您可能还需要将整个内容添加到SecurityDisabler中。

using (new SecurityDisabler()) {
    var templateField = item.Template.AddField("Field name", "Section name");
    using (new EditContext(templateField.InnerItem)) {
        templateField.Type = "Single-Line Text";
    }
}

请尝试使用下一个代码:

 private void AddFieldToTemplate(string fieldName, string templatePath)
{
    const string templateOftemplateFieldId = "{453A3E98-FD4G-AGBF-EFTE-E683A0331AC7}";
    // this will do on your "master" database, consider Sitecore.Context.Database if you need "web"
    var templateItem = Sitecore.Configuration.Factory.GetDatabase("master").GetItem(tempatePath);
    if (templateItem != null)
    {
        var templateSection = templateItem.Children.FirstOrDefault(i => i.Template.Name == "Template section");
        if (templateSection != null)
        {
            var newField = templateSection.Add(fieldName, new TemplateID(new ID(templateOftemplateFieldId)));
            using (new EditContext(newField))
            {
                newField["Type"] = "Text"; // text stands for single-line lext field type
            }
        }
        else
        { 
          add a new section template here 
        }
    }
}

您将使用下一行代码添加新字段:

  AddFieldToTemplate("New field","/sitecore/templates/Sample/Sample Item");

最新更新