Invoice Data – Retrieve Using Observer in Magento 2

admincreate-invoiceevent-observerinvoicemagento2

I am trying to know if create shipment option is selected from admin while creating invoice from admin by creating an observer.
I have tried

sales_order_invoice_register
sales_order_invoice_save_after

events .
My observer is :

<?php

namespace Nmaespace\Module\Observer;

class Invoice implements \Magento\Framework\Event\ObserverInterface
{

/**
 * Execute observer.
 * @param \Magento\Framework\Event\Observer $observer
 * @return $this
 */
public function execute(\Magento\Framework\Event\Observer $observer)
{

    $invoice = $observer->getEvent()->getInvoice();
    $do_shipment = $invoice->getData('do_shipment');
echo $do_shipment;exit;

}

}    

After all di compile and everything when i try to create an invoice i am getting empty value here .
Can someone please help me how check this.

Best Answer

Try this, In your observer

namespace Vendor\Module\Observer;                                       
class Classname implements \Magento\Framework\Event\ObserverInterface        
{
    protected $_request;

    public function __construct(
        \Magento\Framework\App\RequestInterface $request
    ) {
        $this->_request = $request;
    }

    public function execute(
        \Magento\Framework\Event\Observer $observer
    ) {     
        $postdata = $this->_request->getPost();
        $do_shipment = $postdata['invoice']['do_shipment']; 
        echo $do_shipment;
    }
}

Hope this helps :)

Related Topic