Value checked for requireness and set into node when field is disabled/hidden

Created on 27 July 2018, over 6 years ago
Updated 10 May 2024, 8 months ago

We have a term reference field in one of our contents. In some cases this field is hidden (#access set to FALSE) or disabled (#disabled set to TRUE). This is i.e. the case when using Jammer module or in our case some custom code.

When using Term Reference Tree as widget, editing a node with field hidden/disabled leads to:
- error message about missing required field if field is required
- field value in edited node overwrited with an empty value if field is not required

Using 'select list' or 'check boxes/radio buttons' as associated widget don't lead to this behavior: no 'missing required field' is printed even if field is required, and value is let unchanged after validation.

As far as I can see in function _term_reference_tree_widget_validate() from file term_reference_tree.widget.inc no check are performed against #access nor #disabled.

I changed a little bit the code:

-  if ($element['#required'] && empty($value)) {
+  // if element is hidden (#access is FALSE) or disabled do not check for value
+  $validate = TRUE;
+  if (!$element['#access'] || (isset($element['#disabled']) && $element['#disabled'])) {
+    $validate = FALSE;
+  }
+  if ($element['#required'] && empty($value) && $validate) {

This prevents 'missing required field' when field is hidden/disabled.
But it don't prevent value to be overwritten by 'empty'.
I tried to perform the form_set_value() only if $validate but it didn't changed anything, so I added code to remove field value from $form_state and it finally works as (I) expected:

-  form_set_value($element, $value, $form_state);
+  // set value only if needed
+  if ($validate) {
+    form_set_value($element, $value, $form_state);
+  } else {
+    // needed: the empty value is present and node is modified without that (why?)
+    unset($form_state['input'][$element['#field_name']]);
+    unset($form_state['values'][$element['#field_name']]);
+  }

Now I get the same behavior than for other fields or for that field with an other widget.
I did not attached a patch because I don't understand well why the second part is needed, so I prefer wait for feedback and better knowledge.

Regards.

🐛 Bug report
Status

Needs review

Version

2.0

Component

Code

Created by

🇫🇷France Yannick Perret

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024