简体   繁体   中英

How do I edit a product attribute using PHP during a cart checkout in Magento?

I have a two part question about customizing my Magento store.

When someone buys a downloadable product, I want to generate a licence code and include it in the invoice.

I have added a product attribute called 'license_code' to my product's default attribute set and I want to set its value with php when a customer checks out.

What is the event to observe that will let me access the products in the cart just after they are purchased but before the invoice is created?

I also need to know what script to use to set a product's attribute value during that event.

Thank you for your help!

Possible events are sales_order_place_before or sales_convert_quote_* .

You cannot save your 'license_code' attribute because that will affect all products, a product does not store it's values when ordered. Instead a better idea would be to manipulate the options of an order item.

function salesConvertQuoteItemToOrderItem(Varien_Event_Observer $observer)
{
    $orderItem = $observer->getOrderItem();
    $options = $orderItem->getProductOptions();
    $options['licence_code'] = YOUR-DOWNLOADABLE-CODE-HERE;
    $orderItem->setProductOptions($options);
}

Retrieving the code later is essentially the same process with getProductOptions() , the order item objects are already used on the order view pages so are easy to find and use in your theme.

Ok I think I got it figured out.

I set up my event observers as follows:

<events>
    <sales_order_item_save_before>
        <observers>
            <downloadable_observer>
                <class>Licensing_Catalog_Model_Observer</class>
                <method>generate_licenses</method>
            </downloadable_observer>
        </observers>
    </sales_order_item_save_before>
</events>

and then my observing function as:

public function generate_licenses($observer)
{
    $orderItem = $observer->getEvent()->getItem();
    $options = $orderItem->getProductOptions();
    $options['licence_code'] = 'YOUR-DOWNLOADABLE-CODE-HERE';
    $orderItem->setProductOptions($options);

  return $this;
}

Thank you so much for the help, clockworkgeek!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM