TransWikia.com

Add custom fields to variant snapshot

Craft CMS Asked by Will Law on June 22, 2021

How would I add more information (custom fields) to a variant’s snapshot?

The custom field I’m adding will change over time, but I need it to stay consistent on invoices etc.

2 Answers

Yes using the onPopulateLineItem event. Something like this should work:

craft()->on('commerce_lineItems.onPopulateLineItem', function($event){

    $purchasable = $event->params['purchasable'];
    $lineItem = $event->params['lineItem'];

    $lineItem->options = array_merge(
      $lineItem->options,
      ['customFieldLabel'=>$purchasable->customField]
    );

});

Correct answer by Luke Holder on June 22, 2021

For Craft 3 Nathaniel from Pixel & Tonic helped us with the below:

In the following example, I am adding the titles of a category relationship field productColours to the snapshot but only for the products in the product type of clothing.

// Modify product snapshot
Event::on(Variant::class, Variant::EVENT_AFTER_CAPTURE_PRODUCT_SNAPSHOT, function(CustomizeProductSnapshotDataEvent $event) {
    $variant = $event->sender;
    if (!$variant instanceof Variant) {
        return;
    }

    $product = $variant->getProduct();
    if (!$product || $product->type->handle != 'clothing') {
        return;
    }

    $colours = $product->productColours->all();
    if (empty($colours)) {
        return;
    }

    $event->fieldData['productColours'] = ArrayHelper::getColumn($colours, 'title');
});

You will also need to add

use craftcommerceeventsCustomizeProductSnapshotDataEvent;

Answered by Green17 on June 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP