0

I have been using hook form alter for a webform, to set a default value for a webform added as a block to a page. Below is the code, the code only works for users who have logged, but for anonymous or non logged in user the field is not working with a default value even with else condition or with anonymous check. what is wrong in the code below?

function mytheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
$current_role = \Drupal::currentUser()->getRoles();
if ($form_id == 'webform_submission_add_form'){
  if (in_array("user1", $current_role)) {
     $form['elements']['user']['#default_value'] = 'logged';
    }
  else{
     $form['elements']['user']['#default_value'] = 'not logged';
    }
  if (\Drupal::currentUser()->isAnonymous()) {
     $form['elements']['user']['#default_value'] = 'not logged';
     }
  if (in_array("anonymous", $roles)) {
     $form['elements']['user']['#default_value'] = 
     'not logged';
     }
   }
}

1 Answer 1

1

Webform has the built-in ability to define default values for form fields when they're empty. If I remember correctly, it's in the Advanced section when you configure a field. The default value accepts either a static value or a token. Create a custom token if you want to programmatically generate the default value, then configure the webform field to use that token as the default value.

I recommend doing it this way to not hardcode that logic to a specific form, i.e. you can reuse that token in another form. You can also remove it easily from admin without going into code, should you not want it anymore.

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.