I'm trying to add a tag to a user to match a product that they purchase. Following this answer I get a complaint that the tag already exists, so instead I was thinking I could just find the tag and add it like this?

// the tag will match the product title
$productTitle = $product->title;

$tag = Tag::find()->groupId(1)->title($productTitle)->one();
    'userFieldHandle' => [$tag->id]

I don't get any errors but it also isn't adding the tag. Would appreciate some tips!

1 Answer 1


The syntax is correct, but you're not saving the user. Whenever you change an element, you need to save it in order to persist the changes to the database. The only exception is if you're modifying an element during an EVENT_BEFORE_SAVE or similar event, you might not have to do this since the element will be saved after your code runs anyway.

You can save elements using the craft\services\Elements service:

/** @var craft\servicesElements $elementService */
$elementService = \Craft::$app->getElements();

$success = $elementService->saveElement($user);
if (!$success) {
    // saving failed due to a validation error or other error
  • 1
    Ah so simple! Thanks!
    – supazu
    Commented Apr 11, 2022 at 9:31

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.