Sitecore 如何在通过 Template.AddField(string, string) 添加字段时指定数据字段类型;

Sitecore How to specify Data field type when adding a field by Template.AddField(string, string);

如果我有一个 Sitecore 项目 item 并使用以下方法向其添加数据字段 "My Field":

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

如何指定字段类型。例如 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");

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

然后您可以像这样在模板字段上设置类型:

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