Reputation: 3107
I need to set the Shared property on a lot of template fields to false. Is there an easy way to do this in code without the field IDs changing? I have written the following code but it doesn't seem to update the property.
Sitecore.Data.Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
using (new Sitecore.SecurityModel.SecurityDisabler())
{
try
{
var templates = TemplateManager.GetTemplates(masterDb);
foreach (var template in templates.Values)
{
if (template.FullName.StartsWith("FolderName"))
{
foreach (var field in template.GetFields(false))
{
TemplateManager.ChangeFieldSharing(field, TemplateFieldSharing.None, masterDb);
}
}
}
}
catch (Exception ex)
{
}
}
Upvotes: 3
Views: 790
Reputation: 3551
While the TemplateManager.GetTemplates
call gets you a collection of Template
objects what you need is the TemplateItem
object in order to be able to edit it. You can use the ID to get that from your existingDatabase
object.
You then need to iterate into each TemplateSectionItem
of the template before you can get at the TemplateFieldItem
where you can reach into the InnerItem
property and make a change to the shared field. You also need to mark BeginEdit()
and EndEdit()
so that you can perform the change.
Sitecore.Data.Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
using (new Sitecore.SecurityModel.SecurityDisabler())
{
try
{
var templates = TemplateManager.GetTemplates(masterDb);
foreach (var template in templates.Values)
{
if (template.FullName.StartsWith("FolderName"))
{
var tmpl = masterDb.GetTemplate(template.ID);
foreach (var section in tmpl.GetSections())
{
foreach (var templateFieldItem in section.GetFields())
{
templateFieldItem.BeginEdit();
templateFieldItem.InnerItem[TemplateFieldIDs.Shared] = "0";
templateFieldItem.EndEdit();
}
}
}
}
}
catch (Exception ex)
{
Response.Write("Error" + ex.Message);
}
}
Hope this helps :)
Upvotes: 7