5

The states visible seems to work correct in D7. In D8 I want to test make a field visable if one OR another field have a value. And also when two fields have a value. What I have below works if both fields have a value.

use Drupal\Core\Form\FormStateInterface;
use \Drupal\Core\State\StateInterface;

function mymodule_form_alter(&$form, FormStateInterface     &$form_state, $form_id) {
  if ($form_id == 'node_page_form') {
    $form['field_format']['#states'] = array(
      'visible' => array(
          ':input[name="field_item_type"]' => array('value' => 'tv_show'),
          'or',
          ':input[name="field_extra"]' => array('value' => 'bike'),
      ),
    );
  }
}
1
  • Fix like that : 'visible' => array( array( ':input[name="field_item_type"]' => array('value' => 'tv_show') ), 'or', array( ':input[name="field_extra"]' => array('value' => 'bike') ), ), Jan 24 '20 at 10:04
11

Try the below code .It works .

$form['field_item_type'] = [
  '#type' => 'select',
  '#title' => $this->t('Title'),
  '#description' => $this->t('Title must be at least 5 characters in length.'),
  '#options' => ['tv_show'=> 'Tv show','serials' => 'Serials']
];
$form['field_extra'] = [
  '#type' => 'select',
  '#title' => $this->t('Title'),
  '#description' => $this->t('Title must be at least 5 characters in length.'),
  '#options' => ['movie' => 'movie','chair'=>'Chair'],
];
$form['field_format'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Title'),
  '#description' => $this->t('Title must be at least 5 characters in length.'),
  '#required' => TRUE,
];
$form['field_format']['#states'] = [
  'visible' => [
    [
      [':input[name="field_item_type"]' => ['value' => 'tv_show']],
      'or',
      [':input[name="field_extra"]' => ['value' => 'movie']],
    ],
  ],
];
1
  • Thanks. Helped a lot :)
    – user9589
    Jun 13 '19 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.