Skip to content

Instantly share code, notes, and snippets.

@AugustMiller
Last active June 6, 2021 00:57
Show Gist options
  • Save AugustMiller/acda83f0321ddd24e94c9ee39416ed03 to your computer and use it in GitHub Desktop.
Save AugustMiller/acda83f0321ddd24e94c9ee39416ed03 to your computer and use it in GitHub Desktop.
Craft Commerce: Add user to a group when they make a purchase
<?php
namespace modules\mymodule;
use Craft;
use craft\elements\User;
use craft\helpers\ArrayHelper;
use yii\base\Event;
use craft\commerce\elements\Order;
class MyModule extends Module
{
/**
* @var int ID of the special group.
*/
const MAGIC_GROUP_ID = 123;
/**
* @var int Purchasable ID that triggers adding someone to the special group.
*/
const MAGIC_PURCHASABLE_ID = 456;
public function init()
{
parent::init();
Event::on(
Order::class,
Order::EVENT_AFTER_COMPLETE_ORDER,
function (Event $e) {
$order = $e->sender;
$lineItems = $order->getLineItems();
$user = $order->getUser();
// Were they a guest?
if (!$user) {
return;
}
// Nothing to do if the order doesn't contain our magic purchasable!
if (!in_array(self::MAGIC_PURCHASABLE_ID, ArrayHelper::getColumn($lineItems, 'purchasableId'))) {
return;
}
// (The above could be a more sophisticated check for, say, whether any products are related to a specific category… or even to grab a `Group ID` from a field on the purchased product!)
// Fetch just the existing Group IDs:
$groupIds = ArrayHelper::getColumn($user->getGroups(), 'id');
// Push in the new one:
$groupIds[] = self::MAGIC_GROUP_ID;
// Assign them back to the user, committing to the database:
Craft::$app->getUsers()->assignUserToGroup($user->id, $groupIds);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment