Business needs are constantly evolving, and developers have to keep up by updating existing AEM components to reflect ongoing changes. Sometimes it is necessary to add a new field with a predefined default value to an existing dialog. Upon testing the changes, we discovered an inconsistent behaviour: the default is only applied to newly created components. If the component has been edited even once, the defaults are not applied.
What is the reason for this inconsistency? AEM Granite Forms operate using a concept called “freshness.” The form is considered “fresh” if it hasn’t been edited at all. To be more precise, the algorithm matches
jcr:lastModified / cq:lastModified properties.
By default, Granite checks form freshness and applies the default value only if the form is fresh. There is another mode in which the form ignores the freshness and uses the default value whenever there is no data available. Unfortunately, these modes are available for modification only in the Granite form component, not in the Granite dialog.
Can we change this? For most of the fields, yes! For Select fields the solution is straightforward; just add a forceIgnoreFreshness boolean property to your Select field. This property does exactly what it says; it ignores form freshness and always applies the default if no value has been chosen.
But what about other fields? Unfortunately, as of AEM 6.5, they don’t have this handy property. One way to solve this problem is to write a custom UI clientlib, which will check whether the field has a defined value and set a default if it does not. There’s also a simpler way. You can use AAT’s DependsOn plugin, which will allow you to easily set defaults with the help of a “set-if-blank” action.
Checkboxes and switches are still tricky, however. Once the field is rendered on UI, it is impossible to tell the difference between a not configured checkbox and an unchecked checkbox. There are still some workarounds:
- invert the checkbox meaning so that it is disabled by default (e.g., “Enable Dark Mode” => “Disable Dark Mode”), as described in this article
- write a content script to enable checkboxes in already existing components
We hope that these tips will help you to manage default values in Granite dialogs and provide a consistent experience for AEM authors.
Author: Liubou Masiuk