Magento: Firing Events on Shipping Address Change via Admin
As an experienced Magento developer, I often encounter questions about capturing events triggered within the admin interface. In this case, you’re looking for an event that fires right after updating the shipping address of an order via the Magento admin.
Understanding Magento’s Event System
Magento uses a publish-subscribe pattern for its event system. An observer is a subscriber to these events. When an event occurs (e.g., a model is saved), any observers subscribed to that event will have their methods called with relevant data.
The Right Event for Your Scenario
The event you’re looking for is sales_order_address_save_after. This event fires after an order address (either billing or shipping) has been saved, including updates via the admin interface.
Here’s how to create an observer for this event:
- Create a new module configuration file: In your custom module’s
etcfolder, create a new XML file calledevents.xml. Add the following content:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/events.xsd">
<event name="sales_order_address_save_after">
<observer name="your_module_name_order_address_saved" instance="YourCompany\YourModuleName\Observer\OrderAddressSavedObserver"/>
</event>
</config>
- Create the observer class: In your custom module, create a new file under
Observerfolder:OrderAddressSavedObserver.php. Implement this class:
namespace YourCompany\YourModuleName\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Model\Order\Address as OrderAddress;
use Psr\Log\LoggerInterface;
class OrderAddressSavedObserver implements ObserverInterface
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$address = $observer->getEvent()->getData('order_address');
if ($address instanceof OrderAddress) {
$this->logger->info('Shipping Address Saved: ' . json_encode($address->getData()));
// Add your custom logic here.
}
}
}
- Clear cache: After adding or modifying observers, clear the Magento cache (
php bin/magento cache:clean).
Conclusion
In this blog post, we’ve identified and implemented an observer for the sales_order_address_save_after event in Magento 2. This event is perfect for capturing changes to shipping addresses made via the admin interface.
Remember, proper module configuration and clearing the cache are crucial steps when working with events and observers in Magento.
For a comprehensive guide on building custom modules in Magento 2, I recommend checking out our detailed tutorial series at LaravelCompany.
Happy coding! Let me know if you have any other questions related to Magento development.