filter sales invoice grid collection based on order_id in Magento 2

1. Create di.xml inside the app/code/Vendor/Module/etc/. And add the following plugin to your di.xml file.

<?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="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
    <plugin name="Vendor_Module::aroundGetReport" type="Vendor\Module\Plugin\CollectionFactory" sortOrder="1"/>
  </type>

</config>

2. Create plugin class file CollectionFactory.php inside the  app/code/Vendor/Module/Plugin/

<?php
/**
 * Vendor Desc.
 *
 * @category  Vendor Category
 * @package   Vendor_Module
 * @author    Vendor name
 * @copyright Copyright (c) Vendor (https://example.com)
 * @license   https://example.com/license.html
 */

namespace Vendor\Module\Plugin;

use Magento\Framework\Data\Collection;
use Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory as OrigFactory;

/**
 * Class CollectionFactory
 */
class CollectionFactory
{
    /**
     * Const SALES_ORDER_INVOICE_GRID_DATA_SOURCE: contains source name
     */
    const SALES_ORDER_INVOICE_GRID_DATA_SOURCE = 'sales_order_invoice_grid_data_source';

    /**
     * @var Collection[]
     */
    protected $collections;

    /**
     * @param array $collections
     */
    public function __construct(
        array $collections = []
    ) {
        $this->collections  = $collections;
    }

    /**
     * Get report collection
     *
     * @param OrigFactory $subject
     * @param \Closure $proceed
     * @param string $requestName
     * 
     * @return Collection
     * @throws \Exception
     */
    public function aroundGetReport(
        OrigFactory $subject,
        \Closure $proceed,
        $requestName
    ) {
        $result = $proceed($requestName);

        $orderId = 2;

        if ($requestName == self::SALES_ORDER_INVOICE_GRID_DATA_SOURCE) {
            //here order_id is custom column of sales_invoice
            $result->addFieldToFilter("main_table.order_id", $orderId);
        }
        
        return $result;
    }
}



































Leave a comment

Your email address will not be published. Required fields are marked *