如果我有一个Sitecore的项目item
和我使用的数据字段“我的字段”添加到它:Sitecore如何在通过Template.AddField添加字段时指定数据字段类型(字符串,字符串);
item.Template.AddField("My Field", "Data");
如何指定字段类型吧。例如Single-Line Text
如果我有一个Sitecore的项目item
和我使用的数据字段“我的字段”添加到它:Sitecore如何在通过Template.AddField添加字段时指定数据字段类型(字符串,字符串);
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 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";
}
}
请尝试使用下面的代码:
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");
非常感谢。 'xx.Type =“单行文本”;'我真的很想念。 – Kamran