I have added additional fields to my user profiles. I need to be able to change and save these via my plugin. How do I set those values before calling
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It only takes a minute to sign up.Sign up to join this community
You use setContentFromPost method on the UserModel if you are posting to your plugin, like so (this is what happens when you save your profile in the control panel):
$user->setContent([ 'fields' => ['field1' => 'value'] ])
Behind the scenes, that runs the setAttributes method.
Fred got me pointed down a path. Not sure why this works, perhaps someone can explain it to me. This is what I ended up doing.
$initialCredits = 100; $user = craft()->users->getUserById(craft()->userSession->getUser()->id); $user->getContent()->initialCredits = $initialCredits; craft()->users->saveUser($user);
Now, why getContent() worked and setContent() doesn't confuses me. I would think that since I am setting content and not getting it, I should use getContent(). Unless I am on the other side of the model somehow.
Fred is definitely on the right path -- the setContent() call works just fine and makes a lot more sense then using getContent():
$initialCredits = 100; $user = craft()->userSession->getUser(); $user->setContent(['initialCredits' => $initialCredits]); craft()->users->saveUser($user);
P.S. The way you're getting the current user is redundant. Just use