Score:0

How to set a webform default value for anonymous user?

us flag

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';
     }
   }
}
Score:1
in flag

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.

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.