0

I created a block in which I called a form inside the build() function. The form class has elements like radio button, input field type number, and submit button. I added a state condition to make the number field and submit button only visible on a certain condition of radio button.

The submission button is working correctly based on state condition, but not the number input field.

Does anyone has any idea?

$form['age'] = [
  '#type' => 'number',
  '#min' => 0,
  '#title' => $this->t('age'),
  '#default_value' =>'',
  '#states' => [
    'visible' => [
      [':input[name="marital_status"]' => [['value' => 'single'],['value'=>'couple']]],
    ]
  ],
];

$form['mybutton'] = [
  '#type' => 'submit',
  '#value' => $this->t('button'),
  '#states' => [
    'visible' => [
      [':input[name="marital_status"]' => [['value' => 'single'],['value'=>'couple']]],
    ]
  ],
];

$form['marital_status'] = [
  '#type' => 'radios',
  '#title' => $this->t('Marital status'),
  '#options' => [
    'single' => $this->t('single'),
    'couple' => $this->t('couple')
  ]
];
2
  • I don't think you can have an array of arrays with values for conditions to work. Make it look more like lullabot.com/articles/form-api-states and simply repeat the line and have one value per line or try => ['value' => 'single','value'=>'couple']],.
    – leymannx
    Mar 29 at 17:26
  • @leymannx thanks, I tried but it did not work, one condition was missing as well, actually It is an or condition. It seems like something is overriding the state conditions Mar 30 at 8:43
0

I had to override the twig files for the form-element so some classes were missing like js-form-item' and 'form-item'. After adding thoses classes in the twig file, the states worked.

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.