I am inspecting my cart when the user visits /commerce/cart
and if the cart contains a specific product, I want to alert the user that they can redeem a credit for "x" item. If the users chooses to use the credit, I would like to assign the qualifying product a discount.
...
if ($lineItems) {
foreach ($lineItems as $lineItem) {
foreach ($lineItem->purchasable->product->foo as $bar) {
...
// qualifying product found - return json to javascript
...
}
...
$discount = new commerce_DiscountModel();
...
??
// apply discount to cart/update ui via javascript to reflect discount
I'm able get all the way up to creating a new discount. I assume I start by creating a new discount model and populate it with the price of the product I am wanting to discount? I'm not really sure where to start - thank you for any suggestions!
EDIT
First off, thank you, Jeremy for your help. I (think) I am slowly starting to understand. I don't understand how or why the handler is or isn't getting called.
Here is my updated main plugin file:
MyPlugin.php
public function init()
{
error_log(__FUNCTION__); // this is logged
craft()->on('commerce_discounts.onBeforeMatchLineItem',
[
craft()->myPlugin,
'onBeforeMatchLineItemHandler'
]
);
...
}
Then my service file looks like this:
MyPluginService.php
class MyPluginService extends BaseApplicationComponent
{
public function onBeforeMatchLineItemHandler($event)
{
// this method never gets executed
$cart = craft()->commerce_cart->getCart();
$lineItem = $event->params['lineItem'];
$discount = $event->params['discount'];
error_log('line item: ' . $lineItem);
error_log('discount: ' . $discount);
}
...
}
If I change the name of the handler to "myPluginz" or something that doesn't exist, it throws an error, so I know I have the right syntax at least.
The handler was actually called once, but now it never gets executed. The product I have in my cart is promotable, and is not excluded from any sale. So it seems I am matching the criteria needed.
I also tried this straight from the docs.
public function init()
{
error_log(__FUNCTION__); // this is logged
craft()->on('commerce_discounts.onBeforeMatchLineItem', function ($event) {
error_log(print_r($event, true)); // this is not executed
});
}
I don't understand what I've done wrong to cause the event not to fire.
EDIT 2
Well, I think I have finally managed to get out of my own way. I'll update this thread as I progress through.