1

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()->users->saveUser($user);

3 Answers 3

4

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->setContentFromPost('fields');

There is also a setContent method, which takes a ContentModel or an array:

$user->setContent([ 'fields' => ['field1' => 'value'] ])

Behind the scenes, that runs the setAttributes method.

2
  • That would have worked if the data were coming from the form post I suppose. But I am entering calculated data. Commented Sep 26, 2014 at 17:32
  • I added the setContent method. Haven't tested either, but seems like it should work. In general, you should check out the UserModel and the underlying BaseElementModel. Commented Sep 26, 2014 at 18:34
2

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.

1
  • 2
    The User Model is 'getting' content for itself — all about your perspective I guess. ;) Glad you figured it out. This helped me as well. Thanks. Commented Sep 26, 2014 at 20:37
1

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 craft()->userSession->getUser() instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.