2

I basically just want to set the value of a users field to a different number if something happens, so that the user field is actually updated in the CMS. Can I do that without creating a form? So like if I had a custom user field I wanted to update in twig and actually have it change the data in the CMS. I know you can do this with a user/save-user form, but I don't really want a form for this because I don't want it to actually be changed by the user.

1 Answer 1

3

Yes, it's possible via the special Twig do tag, which basically enables you to call methods without returning (i.e. outputting) anything (which is what happens with nearly every other Twig expression).

Assuming the "users field" is a custom field attached to the users' field layout (and you've got a user variable in your Twig template referring to a User element), something like the below should work:

{% do user.setFieldValue('fieldHandle', 123456) %}
{% do craft.app.elements.saveElement(user) %}

What the above does, is first setting the custom field value for a field with the handle fieldHandle to a value 123456 on the user element, via the setFieldValue() method (which is available for all Craft element types). Then, the user is (re)saved using the Elements::saveElement() method (which is what Craft uses to save elements under the hood).

In PHP, the same thing would look like this:

$user->setFieldValue('fieldHandle', 123456);
Craft::$app->getElements()->saveElement($user);
5
  • 1
    Thank you so much! Mar 4 at 0:50
  • Sorry to hijack - is it possible to create a user in this way?
    – iamkeir
    May 23 at 14:03
  • 1
    @iamkeir Technically yes, I think so. Probably not a good idea, in any case it’s going to be difficult to really answer in a comment so you should probably create a new question for it :) May 23 at 20:43
  • @MatsMikkelRummelhoff ah the old "just because you can, doesn't mean you should" :) yeah I'll post a new question, thanks.
    – iamkeir
    May 25 at 10:06
  • For anyone interested, specific query about creating a user: craftcms.stackexchange.com/questions/39591/…
    – iamkeir
    Jun 25 at 11:16

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.