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.

0

1 Answer 1

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>
3
  • 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.
    – AJ -
    Commented Dec 10, 2018 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
    Commented Dec 10, 2018 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 Commented Dec 10, 2018 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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