How can we set custom fields per cart line item?

Achieving this in the current state of shopware 6 seems to be quite a tedious task.

I was surprised this was rather difficult to achieve as it seems quite a common use case when working with eCommerce frameworks, especially within the enterprise sector.

To be able to store information on order item level I had to do the following (for sure this might not be best practice but it works, maybe it will help somebody):

  1. Find a way to add custom data to your cart (line) items.

Line items are stored inside the cart table, to be specific in a serialized form inside the cart column.
(This implementation for sure raises some questions but it is what it is, I guess)

You want to find a way to add custom data to the line items stored there. In my case I rewrote the CartLineItemController (\Shopware\Storefront\Controller\CartLineItemController::addLineItems) to store additional data on line item level.

  1. Create a new Struct class (inheriting from \Shopware\Core\Framework\Struct\Struct) that will then be used to extend a line item (at the point where you add your custom data).

  2. Add your custom data to the line item via your newly created custom struct. It works like this:

$lineItem->addExtension(‘my_custom_struct’, new MyCustomStruct($myCustomData));

  1. Finally, as the custom data is now stored inside the cart item you want to make sure it gets copied to the order line items (table order_line_item) when the order gets placed.
    For that further rewriting is required.
    I rewrote \Shopware\Core\Checkout\Cart\Order\Transformer\LineItemTransformer::transform for this.
    You can utilize custom fields as per documentation (https://docs.shopware.com/en/shopware-platform-dev-en/internals/core/data-abstraction-layer/custom-field), as they are supported for order line items.

if ($lineItem->getExtension(‘my_custom_struct’)) {
    $myCustomFieldData = [‘my_custom_field’ => $lineItem->getExtension(‘my_custom_struct’)->getMyCustomData()];
}

$data = [
    ‘id’ => $id,
    ‘identifier’ => $lineItem->getId(),
    ‘productId’ => $productId,
    …
    ‘customFields’ => $myCustomFieldData
];

That’s it. The custom data is now stored inside a custom field on the order line item and is accessible as per documentation. 

1 „Gefällt mir“