Magento – How to refresh sales order grid by calling \Magento\Sales\Model\ResourceModel\Grid::refresh method

gridmagento2sales

How to call \Magento\Sales\Model\ResourceModel\Grid::refresh method

I am following this link: blog.sivaschenko.com

<?php
 namespace Vendor\OrderGridSync\Controller\Index;
 class Sync extends \Magento\Framework\App\Action\Action
{
protected $_pageFactory;
protected $_postFactory;

/**
* @var \Magento\Sales\Model\ResourceModel\Grid[]
*/

protected $grids;
/**
 * @param array $grids
 */
public function __construct(
        \Magento\Sales\Model\ResourceModel\Grid $grids,
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $pageFactory            
        )
{       
        $this->grids = $grids;
        $this->_pageFactory = $pageFactory;
        return parent::__construct($context);            
}

public function execute()
{
    /**
     * Refresh grids list
     *
     * @param int $orderId
     * @return $this
     */
    foreach ($this->grids as $grid) {
    /**
     * @var \Magento\Sales\Model\ResourceModel\Grid[]
     */
    $grid->refresh(81, "affiliate_information");
    }
    exit;
}              
}

Getting

1 exception(s):
Exception #0 (BadMethodCallException): Missing required argument 
$mainTableName of Magento\Sales\Model\ResourceModel\Grid.

Best Answer

You need to specify the 3 required Params via Factory Creation Logic of Magento.

Something as follows Inject \Magento\Sales\Model\ResourceModel\GridFactory $gridInterface in the constructor and when you use it

$this->gridFactory->create(
            [
                'mainTableName' => 'sales_order',
                'gridTableName' => 'sales_order_grid',
                'orderIdField' => 'entity_id',
            ]
        )->refresh(1);

This way you can give values to required params of constructor. The first param of Context Object is handled by Magento so that need not be given & in the same way other optional params can also be given a value.