0

I am trying to assign a user role at registration using Webforms in Drupal 8. Is this possible or is there another form module that would do it better? I have two user roles 'Venue' and Artist' which will be used throughout the site still using Webforms to enter data specific to user role. New to D8. Thank you.

2
  • You manually create the user with data submitted trough a webform?
    – h3rj4n
    Commented May 28, 2017 at 10:44
  • Thank you. I want the user role (either Venue or Artist) to be assigned automatically when the Webforms form has been submitted during registration. Thanks Commented May 28, 2017 at 11:34

2 Answers 2

2

Oneway you can do is using hook_form_alter()

function MYMODULE_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
     foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = '_add_role_submit';
        }
      }
}
/**
 * Implements submit to set role to user.
 */
function _add_role_submit(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
// HERE YOU CAN SET ANY ROLE FOR USER.
}

Another way is using hook_user_insert()

use Drupal\user\UserInterface;
function MYMODULE_user_insert(UserInterface $user) {
  // HERE YOU CAN SET ANY ROLE FOR USER.
}
0
0

Above form alter solution didn't work for me and I don't want to use hook_user_insert() as I want to assign the role only when the user is created from user/register form, not from Admin interface. So I found a solution myself and sharing here if it helps any one else.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function member_portal_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    array_unshift($form['#validate'], "_add_default_role_validate"); 
}
/**
 * Implements _add_default_role_validate.
 */
function _add_default_role_validate(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    // Add default roles here
    $form_state->setValue('roles', [
       'authenticated',
        'venue_creator',
        'supplier_creator' 
    ]);
}

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.