I have a custom user field 'myuserfield'

How do I save a value to this field via a plugin in Craft3?

Here is my current attempt.

    $myvar = '12345';
    Craft::$app->getUser()->getIdentity()->setFieldValue('myuserfield', $myvar);
    $myid = Craft::$app->getUser()->getIdentity()->getFieldValue('myuserfield');

When I echo $myid it does, in fact, give me the new value ($myvar or 12345) but when I check the control panel the value is not saved.


I used August's answer, but fixed it:

Put this at the top:

use craft\elements\User;

Then the updating code

$myUser = Craft::$app->getUser()->getIdentity();
$myUser->setFieldValue('fieldHand', 'value');

Craft::$app->getElements()->saveElement($myUser, false);

Be sure and stash a reference to the User element you want to edit:

$myUser = Craft::$app->getUser()->getIdentity();
$myUser->setFieldValue('myUserField', 'New Field Value');

if (Craft::$app->getElements()->saveElement($myUser)) {
    echo "User saved.";

Otherwise, you may end up repeatedly fetching the stale record out of the database, instead of saving the modified instance.

Note: The similarly-named Craft::$app->getUsers() is a method for getting the Users Service instance, which is responsible for saving users. Not to be confused with Craft::$app->getUser(), which is a (Yii) method for fetching the current user (the subsequent call to getIdentity() retrieves the Craft Element for the user).

  • 1
    I get this error now - Calling unknown method: craft\services\Users::saveUser() Nov 29 '18 at 6:47
  • 1
    @DavidAaronMcInnis Sorry! Updated the answer—took a bad guess at the method, but it turns out you save Users just like any other Element, via the Elements service. Nov 29 '18 at 23:21

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.