I’m a Magento developer and therefore I save entities. I’m used to it and using a class to set all properties on it is a great way to interact with an entity.
Shopware doesn’t. To create a new entity you call
create on a repository and pass an array to it.
Like this example from the docs:
$this->productRepository->create([ [ 'name' => 'Example product', 'productNumber' => 'SW123', 'stock' => 10, 'taxId' => $this->getTaxId($context), 'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 50, 'net' => 25, 'linked' => false]], ] ], $context);
So, what is the problem with my approach?
What IS my approach actually?
$doc = new \Shopware\Core\Checkout\Document\DocumentEntity(); $doc->setOrder($order); $doc->setOrderId($orderId); $doc->setFileType($fileType); $doc->setDeepLinkCode($deepLinkCode); $this->documentRepository->create($doc->getVars(), $context);
This throws a ton of errors, e.g.
[2023-03-14T18:22:33.836634+00:00] winkelwagen.importinvoices.EMERGENCY: There are 4 error(s) while writing data. 1. [/] Expected data to be array. 1. [/] Expected data to be array. 1. [/] Expected data to be array. 1. [/] Expected data to be array.  
Beside the fact, that these error messages are horrible and meaningless, what they say is “You tried to save something which doesn’t have the expected format”.
To save an order for example you need to define the id:
['id' => $order->getId()]
$doc->getVars() does extract all properties from the entity, but unfortunately doesn’t call getVars recursively on all object which are inside of the entity. And as you can expect an OrderEntity is no array 🤷.
Solution: Don’t use
getVars(), but build your arrays from hand.
Ein Kommentar zu “Shopware: Save new entity – don’t use getVars()”
While it is not recommended, and it’s _the shopware way_ to use arrays for your data, you can actually do `$entity->jsonSerialize();` to get a “shopwareproof” array. However it’s not foolproof, and might not work in all cases.
Better to lose your Magento habits and just use arrays 😉