The ability to add custom fields to an existing content module in Sitefinity CMS provides flexibility to achieve a various range of scenarios.
One of these fields is the Choice Field. It allows users to select one of the predefined values, which can later be accessed via code, and, for example, provide filtering based on this field on the frontend. However, if we want to have a drop down containing all the possible values of the field, they need to be hardcoded manually.
To avoid doing this and to prevent typos, we can use the API to tap directly into the definitions and pull all the values from there, allowing us to bind them to a drop down for example.
First, we need to get one of the backend views (Edit/Insert) and from there we will have access to the CustomFieldsSection and the field we are after.
using
System;
using
System.Linq;
using
Telerik.Sitefinity.Configuration;
using
Telerik.Sitefinity.Modules.Libraries.Configuration;
using
Telerik.Sitefinity.Web.UI.ContentUI.Views.Backend.Master.Config;
using
Telerik.Sitefinity.Web.UI.Fields.Config;
var conf = Config.Get<LibrariesConfig>();
var viewDef = conf.ContentViewControls[
"DocumentsBackend"
].ViewsConfig[
"DocumentsBackendEdit"
]
as
DetailFormViewElement;
var section = viewDef.Sections[
"CustomFieldsSection"
];
var mcFieldDefinition = section.Fields[
"CustomField1"
] asChoiceFieldElement;
var choices = mcFieldDefinition.Choices;
List<
string
> collection =
new
List<
string
>();
foreach
(var item
in
choices)
{
colletion.Add(item.Text);
}
Dropdownlist1.DataSource = collection;
Dropdownlist1.DataBind();
Here is a video of code walktrough.
Stanislav Velikov
Stanislav Velikov is a Tech Support Engineer at Telerik. He joined the Sitefinity Support team in April 2011.