A button in my custom Content Editor selector validates the whole form - how do I stop it, and can I read unsaved field values?
Question
A button in my custom Content Editor selector validates the whole form - how do I stop it, and can I read unsaved field values?
Answer
Why the whole form validates
Content Editor configures Formik differently in the two panels:
| Panel | validateOnChange | validateOnBlur |
|---|---|---|
| Edit | false | default - true |
| Create | false | false |
So editing an existing node validates on blur. Clicking a button inside your
selector moves focus out of the field, that counts as a blur, and the form-level
validate runs across every section. Creating a node does not show the problem,
which is why it often looks intermittent.
Changing a value does not validate - validateOnChange is off in both panels.
If you are seeing validation, it is blur or an explicit call, not the edit itself.
The fix
Pass false as the third argument to setFieldTouched. That argument is
Formik's shouldValidate, and it defaults to on:
const {setFieldValue, setFieldTouched} = useFormikContext();
setFieldValue(field.name, newValue);
setFieldTouched(field.name, true, false); // <- the false is what stops validation
Jahia's own code does exactly this - the ChoiceList "select all" action and the
system-name sync both pass false. Note that not every built-in does: the
unset-field action calls setFieldTouched(field.name) with no third argument, so
do not treat every in-tree example as the pattern to copy.
Also give the button an explicit type. A <button> with no type inside a
form defaults to type="submit":
<button type="button" onClick={...}>
If the button must not steal focus at all, handle onMouseDown and call
preventDefault() so the field never blurs.
Reading unsaved values of other fields
Yes - useFormikContext() gives you the live form state, including edits the user
has not saved:
const {values} = useFormikContext();
const other = values['jnt:myComponent_myOtherProperty'];
Two things to get right:
- The key is not the JCR property name. It is
<fieldSetName>_<jcrPropertyName>, where the prefix is the node type or mixin that declares the property. - Do not hardcode that key. Look the field up in the sections, which you get
from the editor context, and use its
.name. Jahia's own handlers do this rather than building the string.
values is the uncommitted form state, so it reflects what is on screen now, not
what is stored in the JCR.
Related
Can a custom Content Editor selector update two properties at once? covers writing to another field, including the three ways a second value is silently dropped on save.
This article was drafted with AI assistance, then reviewed and curated by Jahia Customer Support engineers before publication.