How empting invisible field in Drupal 8?

1.3k views Asked by At

I'm using this in node add form alter to hide field 'field_obyavlenie_ploschad_uch':

$form['field_obyavlenie_ploschad_uch']['#states'] = [
  'invisible' => [
    'select[name="field_obyavlenie_rubrika"]' => ['value' => '4524'],
  ]
];

But if user enter any value in this field (before the field was hiding) I see this value in Node view.

I'm trying empty field value, but it not working:

$form['field_obyavlenie_ploschad_uch']['#states'] = [
  'empty' => [
    'select[name="field_obyavlenie_rubrika"]' => ['value' => '4524'],
  ]
];

How empting invisible field?

1

There are 1 answers

0
baikho On

Following the comment of @2pha, you won't achieve this with the Form API states.

If you actually want the field to be emptied, you will have to add a custom validation or submit handler and unset the value.

However if you're not too bothered about the persisted value in the database, then you could leverage this in a preprocess hook (function). For your use case this would be a node preprocess hook and unset the value that should be invisible when another field has a specific value:

/**
 * Prepares variables for node templates.
 *
 * @see template_preprocess_node()
 */
function YOUR_MODULE_preprocess_node(&$variables) {
  /* @var $node \Drupal\node\NodeInterface */
  $node = $variables['node'];
  // Look for a node field value and act accordingly.
  if ($node->get('field_obyavlenie_rubrika')->value == '4524') {
    unset($variables['content']['foo']['field_obyavlenie_ploschad_uch']);
  }
}