4

Is there a way to dynamically change the value of a field in Sitecore based on other fields' values, something like computed fields in RDBMS?

For example, let's say we have a template that has the following fields:

  • First Name
  • Last Name
  • Full Name

What I need to accomplish here is to change Full Name everytime a First Name or Last Name has changed.

7

If you really need to dynamically change value of Full Name field, you can create your own ItemSave handler which will change this field for particular item templates.

You can use something similar:

public class CustomItemSaveEventHandler
{
    //master database name
    public static readonly string Master = "master";
    //sample template id
    public static readonly string TemplateIdItem = "{your_template_id_goes_here}";

    public void OnItemSaved(object sender, EventArgs args)
    {
        Item item = Event.ExtractParameter(args, 0) as Item;
        if (item != null && item.Database.Name.ToLower() == Master)
        {
            if (item.TemplateID.ToString() == TemplateIdItem )
            {
                item.Editing.BeginEdit();
                item.Fields["Full Name"] = item.Fields["First Name"] + " " + item.Fields["Last Name"];
                item.Editing.EndEdit();
                item.Editing.AcceptChanges();
            }
        }
    }
}

Add some logic when First or Last names are missing and so on.

Don't forget to create a patch file :

<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <events>
      <event name="item:saved">
        <handler type="MyAssembly.MyNamespace.CustomItemSaveEventHandler, MyAssembly" method="OnItemSaved">
        </handler>
      </event>
    </events>
  </sitecore>
</configuration>
  • Thanks, Peter, but this will run for each item save on the tree, which might lead to a performance issue, I'm looking for a simpler approach is available. – Jaffal Dec 10 '18 at 11:46
  • 3
    That is the way to handle this. If you do the check on the template and exit the handler if it's not the required template, you won't get a performance hit on the CM server. Make sure you set the config to not add the handler for the CD roles and you will be fine. – Richard Seal Dec 10 '18 at 12:02
  • 2
    To further improve performance (and prevent infinite loops), you should also check the list of item changes to make sure either the First or Last name fields were changed in this save. See an example of that: sitecore.stackexchange.com/a/14742/342 – Dan Sinclair Dec 10 '18 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.