Role http://lobsterr.me/ en How to add / remove user role programmatically in Drupal 8 ? http://lobsterr.me/post/how-add-remove-user-role-programmatically-drupal-8 <span class="field field--name-title field--type-string field--label-hidden">How to add / remove user role programmatically in Drupal 8 ?</span> <div class="field field--name-f-intro field--type-string-long field--label-hidden field__item"><br /> <br /> </div> <span class="field field--name-uid field--type-entity-reference field--label-hidden"><span lang="" about="/user/1" typeof="schema:Person" property="schema:name" datatype="">LOBsTerr</span></span> <span class="field field--name-created field--type-created field--label-hidden">11/07/2019</span> <div class="field field--name-f-content field--type-entity-reference-revisions field--label-hidden field__items"> <div class="field__item"> <div class="paragraph paragraph--type--l-text paragraph--view-mode--default"> <div class="clearfix text-formatted field field--name-f-text field--type-text-long field--label-hidden field__item"><p>User access system based on roles and in some cases we want to assign role based on specific business requirements. </p> <p>For this we need to load a user first:</p> <pre> <code class="language-php">&lt;?php use Drupal\user\Entity\User; // pass the correct user id here. User:load(4); </code></pre> <p>or we can load current user</p> <pre> <code class="language-php">&lt;?php use Drupal\user\Entity\User; User::load(\Drupal::currentUser()-&gt;id());</code></pre> <p>Then we add a user role </p> <pre> <code class="language-php">// pass machine name of the user. $user-&gt;addRole('administrator'); $user-&gt;save();</code></pre> <p>To remove the role we can use this code</p> <pre> <code class="language-php">// pass machine name of the user. $user-&gt;removeRole('administrator'); $user-&gt;save();</code></pre> </div> </div> </div> </div> <div class="field field--name-f-tags field--type-entity-reference field--label-hidden field__items"> <div class="field__item btn btn-secondary"><a href="/tags/drupal-9" hreflang="en">Drupal 9</a></div> <div class="field__item btn btn-secondary"><a href="/tags/user" hreflang="en">User</a></div> <div class="field__item btn btn-secondary"><a href="/tags/role" hreflang="en">Role</a></div> </div> <section class="field field--name-f-comments field--type-comment field--label-above comment-wrapper"> </section> Thu, 07 Nov 2019 09:56:51 +0000 LOBsTerr 17 at http://lobsterr.me