Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Temporary fix for Magento 2 bug where invoices for PayPal orders do not have address information attached. This mainly shows up in the grid. See https://github.com/magento/magento2/issues/6438
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="C3\Magento2Fixes\Observer\AfterOrderInvoiceAddresses">
<arguments>
<!-- Pass Virtual Invoice Grid type in observer - must be done in DI as virtual -->
<argument name="invoiceGrid" xsi:type="object">Magento\Sales\Model\ResourceModel\Order\Invoice\Grid</argument>
</arguments>
</type>
</config>
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="paypal_express_place_order_success">
<observer name="c3_fixes_update_invoice_address_data" instance="C3\Magento2Fixes\Observer\AfterOrderInvoiceAddresses" />
</event>
</config>
<?php
namespace C3\Magento2Fixes\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Model\Order\InvoiceFactory;
class AfterOrderInvoiceAddresses implements ObserverInterface
{
/**
* @var \Magento\Sales\Model\ResourceModel\Grid
*/
protected $invoiceGrid;
/**
* @var InvoiceFactory
*/
protected $invoiceFactory;
public function __construct(
\Magento\Sales\Model\ResourceModel\Grid $invoiceGrid,
InvoiceFactory $invoiceFactory
) {
$this->invoiceGrid = $invoiceGrid;
$this->invoiceFactory = $invoiceFactory;
}
public function execute(Observer $observer)
{
$order = $observer->getOrder();
// Get all invoices attached to order (likely just 1)
$invoices = $order->getInvoiceCollection();
foreach ($invoices as $invoice) {
// If invoice missed address IDs, set from order
if ($invoice->getShippingAddressId() == null || $invoice->getBillingAddressId() == null) {
$newInvoice = $this->invoiceFactory->create()->load($invoice->getId());
$newInvoice->setShippingAddressId($order->getShippingAddress()->getId());
$newInvoice->setBillingAddressId($order->getBillingAddress()->getId());
// Save address IDs
$newInvoice->save();
// Refresh data in invoice grid
$this->invoiceGrid->refresh($order->getId(), $this->invoiceGrid->getOrderIdField());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment