Create Line Item with custom type Shopware 6

Viewed 48

I would to create a Line Item with custom type. I already created a handler for custom type and registered it in services. This is a code what I have:

`

$lineItem = $this->lineItemFactoryRegistry->create([
    'type' => 'example',
    'id' => $id,
    'quantity' => 1
], $context);
$lineItem->setLabel('myLabel');
$lineItem->setRemovable(true);
$lineItem->setGood(false);

`

The $id variable is a random uuid.

In controller I try to add the line item like this:

`

$this->cartService->add($cart, $lineItem, $context)

` but after run this code I don't see my Line Item in the cart. I need to create and add the line item in controller because I want to create line item after link on my custom <a href=#"> link.

Do You have any idea where can be a problem?

I tried to add custom handler and registered it in services and I also tried to add line item via API (/store-api/checkout/cart/line-item)

1 Answers

You need to persist the cart after making changes to it.

So you need to inject Shopware\Core\Checkout\Cart\CartPersister to your controller as a service.

After making changes to your $cart you need to persist it to the database, so your code should look something like this:

$lineItem = $this->lineItemFactoryRegistry->create([
    'type' => 'example',
    'id' => $id,
    'quantity' => 1
], $context);
$lineItem->setLabel('myLabel');
$lineItem->setRemovable(true);
$lineItem->setGood(false);

$cart->add($lineItem);

$this->persister->save($cart, $saleschannelContext); // Am assuming $context is not an instance of "Shopware\Core\System\SalesChannel\SalesChannelContext", and if not add "Shopware\Core\System\SalesChannel\SalesChannelContext $saleschannelContext" to your controller action as an argument if you haven't.
Related