3

I've got this

    // Creating users through frontend
    Event::on(Users::class, Users::EVENT_BEFORE_ACTIVATE_USER, function(UserEvent $event) {
        $userId = $event->user->id;

        // Allow assigning user groups through the frontend (circumvent elevated user sessions)
        $groupId = Craft::$app->getRequest()->getBodyParam('userGroup');
        if ($groupId) {
            Craft::$app->getUsers()->assignUserToGroups($userId, [$groupId]);
        }

        // This does not work
        Craft::$app->users->getUserById($userId)->setFieldValue('discountPercentage', 15);
    });

Assigning the user group works fine, so I don't get why assigning a field value doesn't. The discountPercentage field is a simple Number fieldtype

I also tried $event->user->setFieldValue('discountPercentage', 15); without success.

Also I tried surrounding 15 in quotes, like '15', but that didn't work either.

Edit:

Submitting the "create user form" through the frontend gives no errors. discountPercentage is just left blank.

  • Why the downvote? If there is a better way for me to ask for help, please tell me so I can improve. That would be constructive, rather than downvoting without explaining why. Thanks. – Stian Karlsen Jan 20 at 14:38
1

If you are going to set the fieldValue, you need to save the element:

    $userObject = Craft::$app->users->getUserById($userId)->one();
    $userObject->setFieldValue('discountPercentage', 15); 
    Craft::$app->elements->saveElement($userObject);

Should do the trick.

  • That works, the only exception being that I needed to remove one() when getting the $userObject. Thanks! – Stian Karlsen Feb 5 at 5:54

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.