Skip to content

Instantly share code, notes, and snippets.

@bossanova808
Created October 7, 2019 02:50
Show Gist options
  • Save bossanova808/279051e9ee522f48c7c2c2860554a815 to your computer and use it in GitHub Desktop.
Save bossanova808/279051e9ee522f48c7c2c2860554a815 to your computer and use it in GitHub Desktop.
Craft Commerce add user to group on product purchase
public function onAfterCompleteOrderHandler($event)
{
// @var Order $order
$order = $event->sender;
// LOGIC FOR SPECIFIC ITEM PURCHASES
$newGroups = [];
foreach ($order->lineItems as $lineItem) {
$id = $lineItem->purchasable->product->id;
if ($id == "10636") {
self::log("Bought FOD eBook, add to group 7");
$newGroups[] = 7;
}
}
if (!empty($newGroups)) {
// assignToGroups does not update the cached user model.
// so instead we get the user from the db.
$user = Craft::$app->users->getUserByUsernameOrEmail($order->email);
if (!$user) {
self::log("No user for $order->email found, can't add to groups...");
return;
}
self::log("New Groups for order->email: $order->email user: $user->email found");
self::log($newGroups);
$groupIds = [];
// Get existing group Ids
foreach ($user->getGroups() as $group) {
$groupIds[] = $group->id;
}
// Now, add the new group Ids
foreach ($newGroups as $xValue) {
$groupIds[] = $xValue;
}
$result = Craft::$app->users->assignUserToGroups($user->id, $groupIds);
self::log("Added to groups is: " . ($result ? "true" : "false"));
}
}
@migswd
Copy link

migswd commented Jan 20, 2020

Hi.
Thank you for this gist. I am just trying to implement this on my website.
So your code is a module I have to implement in my custom plugin. Correct ? :)

@bossanova808
Copy link
Author

Yep, this code is part of a custom module (not a plugin in my case, but it could be either in a module or a plugin).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment