Add/remove roles after submitting a certain webform 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):

&lt;?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-&gt;addRole('styled');
    $user-&gt;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).")."
\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-&gt;id());
$user-&gt;addRole('styled');
$user-&gt;save();