2015-10-09 46 views

回答

1

AddField(...)方法返回添加模板字段(它不有一个类型呢)。

然后,您可以设置这样的模板字段类型:

var templateField = item.Template.AddField("Field name", "Section name"); 

using (new EditContext(templateField.InnerItem)) { 
    templateField.Type = "Single-Line Text"; 
} 

类型值应该对应于字段类型的名称 - 例如Single-Line Text,Rich Text,Grouped Droplist

根据您的安全,你可能还需要在SecurityDisabler添加整个事情。

using (new SecurityDisabler()) { 
    var templateField = item.Template.AddField("Field name", "Section name"); 

    using (new EditContext(templateField.InnerItem)) { 
     templateField.Type = "Single-Line Text"; 
    } 
} 
+0

非常感谢。 'xx.Type =“单行文本”;'我真的很想念。 – Kamran

0

请尝试使用下面的代码:

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"); 
相关问题