1

I am in the process of building a gift card system for a Craft Commerce site. The current process is that the customer will order a gift card and proceed through checkout as with any other item.

The only information passed through the options is the amount, which is used to generate the gift card. The process works perfectly, and the gift card is generated exactly how it is supposed too.

The next step is to modify the line items using the event onBeforeOrderComplete or onOrderComplete. I would like to change the options to include the amount, and the gift card code.

This is the process I have at the moment, which is just one of the many variations that I've attempted. Nothing I do seems to change the options on the order.

craft()->on('commerce_orders.onBeforeOrderComplete', function($event) {
    $order = $event->params['order'];
    $items = $order->lineItems;

    foreach( $items as $key => $item ) {
        $type = $item->getPurchasable()->getProduct()->getType();
        if ($type->handle === 'giftCard') { 
            $options = $item->options;
            $giftcard = new GiftCards_GiftCardModel();

            $giftcard->amount = $item->price;
            $giftcard->balance = $item->price;
            $giftcard->isActive = 1;

            craft()->giftCards->saveGiftCard($giftcard);

            $options['code'] = $giftcard->code;
            $items[$key]->options = $options;
        }
    }

    $order->lineItems = $items;
});

My only other solution is to generate the gift card code when the gift card is added to the cart and change the active status when order is complete. This would solve my problem completely, but it runs the risk of having hundreds or even thousands of gift cards generated and never completely activated.

1 Answer 1

1

I found a solution (possibly temporary) to my problem. Instead of trying to modify the line items via the order itself, I am modifying them directly.

After changing the line item during the for loop, I pass the $item variable back into this code:

craft()->commerce_lineItems->saveLineItem($item);

I'm not entirely sure what the extra impact that is on the number of queries, but considering that most people will only order a single gift card, maybe two, I would imagine that it's not a terrible way to accomplish this.

I'm still open to ideas of a better way to solve my issue, but for now it seems to do the trick.

Your Answer

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

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