Set a field in all the children of an item

343 views Asked by At

I have an Item in sitecore lets say "AddressItem" that has some children. I want to edit a Field "IsMain" in all the child items.

I am using Foreach loop. Is there some better way to achieve this.

foreach (Sitecore.Data.Items.Item child in AddressItem.Children)
{
    using (new SecurityDisabler())
    {
        child.Editing.BeginEdit();
        child.Fields["IsMain"].Value = "0";
        child.Editing.EndEdit();
    }
}
1

There are 1 answers

0
Jason Horne On BEST ANSWER

Its probably faster to set the IsMain fields standard value to 0 then reset all items to that standard value. There is no function for that out of the box but the below code will do it.

This function is a little more robust then your requirement but its the code I have as is.

First you need a user with the correct permissions to replace: ElevatedUserAccount

Next get the list of items you would like to reset the values for then create a list of fields you wish to reset. In your case AddressItem.Children and IsMain.

Finally pass them into the below methods.

public void ResetFields(List<Item> items, List<string> fields)
{
    if (items.Any() && fields.Any())
    {
        foreach (Item item in items)
        {
           ResetFieldsOnItem(item, fields);
        }
    }
}

public void ResetFieldsOnItem(Item item, List<string> fields)
{
    if (item != null && fields.Any())
    {
        using (new Sitecore.Security.Accounts.UserSwitcher(ElevatedUserAccount, true))
        {
            item.Editing.BeginEdit();

            foreach (string field in fields)
            {
                item.Fields[field].Reset();
            }

            item.Editing.EndEdit();
        }
    }
}