If I have a Sitecore Item item
and I add a Data field "My Field" to it using:
item.Template.AddField("My Field", "Data");
How Can I specify the field type for it. e.g Single-Line Text
The AddField(...)
method returns the added template field (it doesn't have a type yet).
You can then set the type on the template field like this:
var templateField = item.Template.AddField("Field name", "Section name");
using (new EditContext(templateField.InnerItem)) {
templateField.Type = "Single-Line Text";
}
The type value should correspond to the name of the field type - e.g. Single-Line Text
, Rich Text
, Grouped Droplist
etc.
Depending on your security you might also need to add the whole thing in a SecurityDisabler
.
using (new SecurityDisabler()) {
var templateField = item.Template.AddField("Field name", "Section name");
using (new EditContext(templateField.InnerItem)) {
templateField.Type = "Single-Line Text";
}
}