User::addRole() and ::removeRole() should be chainable

Created on 1 December 2022, over 1 year ago
Updated 19 January 2023, over 1 year ago

Problem/Motivation

User::addRole() does not return a value, meaning the function be changed.

Steps to reproduce

Execute the following code, where $id is an existing user ID, and $role_id is the machine name of an existing role.

\Drupal::entityTypeManager()->getStorage('user')
  ->load($id)
  ->addRole($role_id)
  ->save();

An error is thrown that save() is called on NULL.

Proposed resolution

User::addRole() should return $this.

Remaining tasks

Write tests.

User interface changes

None.

API changes

None needed - this is for forward compatibility.

Data model changes

None.

Release notes snippet

Methods User::addRole() and User::removeRole() previously did not return a value, and therefore could not be chained. Now both return $self and can be used in chained calls.

Previous:

$user->removeRole('editor');
$user->addRole('contributor');
$user->save();

New:

$user
  ->removeRole('editor')
  ->addRole('contributor')
  ->save();
✨ Feature request
Status

Fixed

Version

10.1 ✨

Component
User moduleΒ  β†’

Last updated about 15 hours ago

Created by

πŸ‡¨πŸ‡¦Canada Jaypan

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

No activities found.

Production build 0.69.0 2024