2

I know that we can achieve this via Rules but unfortunately, there are some known issues that prevent Rules in Drupal 8 to add a role properly.

So I was wondering if it would be possible to programmatically add and remove some roles to an authenticated user after submitting a webform.

For now, I'm simply trying to add a role called styled to the logged-in user, So I created a 'Webform Handler' called webform_handler_role and added that to the webform through UI, but I still can't get it to add the role using the following code (Also note that I have Ajax enabled for the webform):

<?php
namespace Drupal\webform_handler_role\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Webform submission action handler.
 *
 * @WebformHandler(
 *   id = "userrole",
 *   label = @Translation("User Role"),
 *   category = @Translation("User Role"),
 *   description = @Translation("Adds a user role after submission"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
 * )
 */
class UserRoleHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
    $user = \Drupal::currentUser();
    $user->addRole('styled');
    $user->save();
  }
}

And after the form submission I end up with the following error:

"Error: Call to undefined method Drupal\Core\Session\AccountProxy::addRole() in Drupal\webform_handler_role\Plugin\WebformHandler\UserRoleHandler->postSave() (line 28 of /modules/custom/webform_handler_role/src/Plugin/WebformHandler/UserRoleHandler.php).")."

2

\Drupal::currentUser() loads only an Account, but you need a fully loaded entity to modify and save the user:

$account = \Drupal::currentUser();
$user = \Drupal\user\Entity\User::load($account->id());
$user->addRole('styled');
$user->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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