Gabbar
Gabbar

Reputation: 4066

Update value of one field based on another

I have a template two text fields. A user creates an item based on this template and enters content into the first text field.

On item save, I want to be able to manipulate that value, somehow, and write it to the second field when the item is saved.

I have read about 3 ways of doing this - item:saved, item:saving or item save rules engine. I'm looking for an explanation in the difference of these approaches and if you had to choose which one would you pick?

Upvotes: 1

Views: 1510

Answers (1)

RobertoBr
RobertoBr

Reputation: 1801

Item Saved is an event fired after an item has been saved. I wouldn't use that because it will chain events once you want to update again the same item. There is ways to avoid that but I would rather use Item:Saving, which is fired before the item has been saved.

Rules engine, I don't know exactly how it would fit your needs.

A sample of a item saving that changes the item name prior to being saved:

public class ItemNameReplacementEventHandler
{
    /// Called when [item saving].
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="args">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    public void OnItemSaving(object sender, EventArgs args){
        var item = GetContextItem(args);

        if (!ShouldChange(item))
            return;

        //do the replace
        Regex pattern = new Regex(this.ReplaceFromRegexPattern);
        string newName = pattern.Replace(item.Name, this.ReplaceToString);
        item.Name = newName;
    }
    private static Item GetContextItem(EventArgs args)
    {
        return Event.ExtractParameter(args, 0) as Item;
    }
}

Just change the value of a field, or in this case the item name, and it is enough.

The configuration is like this:

<events>
    <event name="item:saving">
        <handler patch:before="handler[@type='Sitecore.Tasks.ItemEventHandler, Sitecore.Kernel']"
                         type="TYPE, ASSEMBLY" method="OnItemSaving">
        </handler>
    </event>
</events>

Upvotes: 5

Related Questions