Magento – Magento 2: How to add custom filters in Orders Report

adminhtmlgridmagento2reports

I have added new checkbox called "Split by Country" as a filter in Orders Report section.

File:

vendor/magento/module-reports/Block/Adminhtml/Filter/Form.php

$fieldset->addField(
        'split_by_country',
        'checkbox',
        [
            'label' => __('Split by Country'),
            'name' => 'split_by_country',
            'data-form-part' => $this->getData('target_form'),
            'onchange' => 'this.value = this.checked;'
        ]
    );

enter image description here

Then I added a new column in grid called "Country".

enter image description here

File:

vendor/magento/module-reports/Block/Adminhtml/Sales/Sales/Grid.php

$this->addColumn(
        'country',
        [
            'header' => __('Country'),
            'type' => 'string',
            'index' => 'country',
            'sortable' => false
        ]
    );

What I want to achieve here is, when a "Split by Country" checkbox is checked then in a grid I want to display entries order by country.

Please suggest me a solution for this.

Thank you

Best Answer

First of all it's very bad practice to change core code. Do not write directly in core files.

To create custom field and custom collection. you need to do following things:

Step 1) Override Order.php with your custom module file by writing as following in etc/adminhtml/di.xml file.

<preference for="Magento\Sales\Block\Adminhtml\Report\Filter\Form\Order" type="<PackageName>\<ModuleName>\Block\Adminhtml\Report\Filter\Form\Order" />

Step 2) Copy vendor/magento/module-sales/Block/Adminhtml/Report/Filter/Form/Order.php file in your module under directory **Block\Adminhtml\Report\Filter\Form**

Step 3) Override Grid.php by writing following in etc/adminhtml/di.xml file.

<preference for="Magento\Reports\Block\Adminhtml\Sales\Sales\Grid" type="<PackageName>\<ModuleName>\Block\Adminhtml\Sales\Sales\Grid" />   

Step 4) Copy file vendor/magento/module-reports/Block/Adminhtml/Sales/Sales/Grid.php in your module under directory Block\Adminhtml\Sales\Sales.

Step 5) Override function _prepareCollection() to write your own custom logic in Block\Adminhtml\Sales\Sales\Grid.php file. Checkout vendor/magento/module-reports/Block/Adminhtml/Grid/AbstractGrid.php file for more information about this function.

File : vendor/magento/module-reports/Block/Adminhtml/Filter/Form.php This is the common block for all report which render common filter across all reports. To override order filter you need to override block vendor/magento/module-sales/Block/Adminhtml/Report/Filter/Form/Order.php. You can see layout file vendor/magento/module-reports/view/adminhtml/layout/reports_report_sales_sales.xml to check which block getting rendered on page.

Related Topic