0

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?

baikho
  • 5,203
  • 4
  • 40
  • 47
Aleksandr
  • 3
  • 3
  • 2
    Are you trying to remove the value that has been entered into the field? The #states can not do that. You can not have "empty" as a state as how you have it in your second example. You can only use empty as a condition. ie, make something "invisible" if other thing is "empty". [Here are the docs for Drupal 7](https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#states), it's pretty much the same in Drupal 8 as far as I know. – 2pha Jun 13 '20 at 12:56
  • Yes I'm trying to remove the value. How I can remove the value if field states "invisible"? – Aleksandr Jun 13 '20 at 13:11

1 Answers1

0

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']);
  }
}
baikho
  • 5,203
  • 4
  • 40
  • 47