Shopware 6 - Tips, tricks and how to's

How to change order states programmatically in Shopware 6

Recently, while browsing the Shopware 6 official forum, I have encountered an interesting thread. One of the fellow developers was struggling with a task to change the default behavior of Shopware 6, so that if a payment state has changed to “in progress”, the state of the whole order should change to “in progress” as well. I have not done this before, so I took it upon myself to try it and learn something from it. I have resolved it successfuly, so let me share the solution with you.

This is a typical use case for a Shopware 6 subscriber. Subscriber is a mechanism, that allows you to run your function, when a certain event happens. You just need to tell Shopware, which method you want to trigger on which event. In our case, we want to subscribe to the ORDER_TRANSACTION_WRITTEN_EVENT. This event is activated every time Shopware writes data to the order_transaction table. That is perfect for our needs, because this table contains information about payments, including payment states. In our function, that will get called immediately after the data is written, we will detect the current payment state. Based on this state, we will set the state of the whole order accordingly. The whole code for changing order states in Shopware 6, based on payment state, can look like this:

This is a class named simply Subscriber, that should be located in a Subscriber subdirectory of your plugin. In order to make things work, you also need to register your subscriber, so that Shopware knows about it. This is done inside an XML file, named services.xml, that should be located in your plugin as well in src/Resources/config subdirectory. It should look like this: