Score:0

Change default value when triggering form #states

kn flag

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

Score:1
kn flag

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");
    }
  }
}
Score:0
gb flag

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.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.