TransWikia.com

Editing a users custom fields from a plugin action Craft 3

Craft CMS Asked by Green17 on October 9, 2020

Does anyone know if there is a block on updating users form an action?

Trying to update a users custom field in craft 3 via plugin in the admin. The admin template calls an ajax call to the action when a drop-down is changed.

This works ok in the base of the plugin, but not in an action.

    public function actionUpdateuser()
    {
        // Update user data
        $userId = 67852;
        $user = Craft::$app->users->getUserById($userId);
        $user->setFieldValue('userCompanyName', 'New Name 2'); 
        $result = Craft::$app->elements->saveElement($user);

        return $result;
    }

The action fires ok and can return other things just does not update the user.

One Answer

You should just reference the field as an object property of the user instead of using setFieldValue. I also use the getElements function instead of using the property, but I don't think that makes much difference. The code below should work.

public function actionUpdateuser() {
    // Update user data
    $userId = 67852;
    $user = Craft::$app->users->getUserById($userId);
    $user->userCompanyName = 'New Name 2'; 
    $result = Craft::$app->getElements()->saveElement($user);

    return $result;
}

Also make sure to add the Craft Users class at the top of the page with:

use craftelementsUser;

Correct answer by Steven B on October 9, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP