By default, my field_taxo has the value 'castle'.

  1. _none
  2. castle (by default)
  3. mansion

The field_taxo is only showing when the role 'marketing' is checked, and becomes required.

 * Implements hook_form_alter().
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
  $forms = ['user_register_form', 'user_form'];
  if (in_array($form_id, $forms)) {
    $form['field_taxo']['#states'] = [
      'visible' => [
        ':input[name="roles[marketing]"]' => ['checked' => TRUE],
    $form['field_taxo']['widget']['#states'] = [
      'required' => [
        [':input[name="roles[marketing]"]' => ['checked' => TRUE]],

Is it possible to set the value to '_none' when the role marketing is not checked ? Because I need the value to be empty for the non-marketing role

2 Answers 2


Found a workaround by adding this :

$form['#validate'][] = '_mymodule_user_validate';

and reseting the value in the validate function

function _mymodule_user_validate(&$form, \Drupal\Core\Form\FormStateInterface &$form_state) {
  if(!in_array('marketing', $form_state->getValue('roles'))) {
    $form_state->setValue('field_taxo', []);
  } else {
    if($form_state->isValueEmpty('field_taxo')) {
      $form_state->setErrorByName('field_taxo', "error");

It is not possible to do this with #states.
Take a look a https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21FormHelper.php/function/FormHelper%3A%3AprocessStates/9.3.x
Only states like enabled, visible, checked, ... are available. You need to add a custom javascript or use ajax to do this.
If you only use this value on server side, you can check if the role marketing is not checked and unset the other value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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