Export admin grid with selected columns

Export admin grid with selected columns

=> How can I remove columns in exported CSV from order grid?

https://magento.stackexchange.com/questions/166610/magento-2-how-can-i-remove-columns-in-exported-csv-from-order-grid

Hello.
Key: What you see is what you export!!!

When you are working with admin grids, when you want to export data from the admin grid, but you know that you these columns of the data grid has hardcoded at the backend in *[grid_id].xml*, Now I will give you a solution for this case you will export exactly columns you have selected. What you see is what you export!!!

Note: I public this post for Middle Developer Level Who can create a Grid on Admin, not for newbie level, you may need to research about create Grid On Admin using ui_component.

You have a grid with IU-Component in admin with an export controller. Something like this.

Admin Report grid

There is no problem with export this grid to a CSV file. But what about when you want to export what you see? Seem like what you see is what you get in CSV file?

Let me do that for you with step by step.
First Step: Register your export button in your: view/adminhtml/ui_component/[grid-view-id].xml

<exportButton name="export_button"  class="Namespace\AdvancedReport\Component\ExportButton">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="component" xsi:type="string">Magento_Ui/js/grid/export</item>
            <item name="displayArea" xsi:type="string">dataGridActions</item>
            <item name="options" xsi:type="array">
                <item name="cvs" xsi:type="array">
                    <item name="value" xsi:type="string">csv</item>
                    <item name="label" xsi:type="string" translate="true">CSV</item>
                    <item name="url" xsi:type="string">my_advancedreport/export/gridToCsv</item>
                </item>
            </item>
        </item>
    </argument>
</exportButton>

Of course, you need a controller to do this thing:

namespace Namespace\AdvancedReport\Controller\Adminhtml\Export;

class GridToCsv extends \Magento\Ui\Controller\Adminhtml\Export\GridToCsv
{
    const ADMIN_RESOURCE = 'My_AdvancedReport::advanced_invoice_report';
}

Second Step: Modify your controller class to use custom Export Model. /code/Namespace/AdvancedReport/etc/di.xml (scope global or Adminhtml)

<type name="Namespace\AdvancedReport\Model\Export\ConvertToCsv">
    <arguments>
        <argument name="metadataProvider" xsi:type="object">Namespace\AdvancedReport\Model\Export\MetadataProvider</argument>
    </arguments>
</type>
<type name="Namespace\AdvancedReport\Controller\Adminhtml\Export\GridToCsv">
    <arguments>
        <argument name="converter" xsi:type="object">\Namespace\AdvancedReport\Model\Export\ConvertToCsv</argument>
    </arguments>
</type>

Custom data provider to get what are selected columns user have selected on Admin.
app/code/Namespace/AdvancedReport/Model/Export/MetadataProvider.php
about the idea I have used \Magento\Ui\Model\BookmarkManagement. to get stored grid for Admin User while User Edit selected or sort-ordered columns of the Report Grid.

namespace Namespace\AdvancedReport\Model\Export;


use Magento\Framework\View\Element\UiComponentInterface;
use Magento\Ui\Component\MassAction\Filter;
use Magento\Framework\Locale\ResolverInterface;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;

class MetadataProvider extends \Magento\Ui\Model\Export\MetadataProvider
{
    /**
     * @var \Magento\Ui\Model\BookmarkManagement
     */
    protected $_bookmarkManagement;

    /**
     * MetadataProvider constructor.
     * @param Filter $filter
     * @param TimezoneInterface $localeDate
     * @param ResolverInterface $localeResolver
     * @param string $dateFormat
     * @param \Magento\Ui\Model\BookmarkManagement $bookmarkManagement
     * @param array $data
     */
    public function __construct(
        Filter $filter,
        TimezoneInterface $localeDate,
        ResolverInterface $localeResolver,
        \Magento\Ui\Model\BookmarkManagement $bookmarkManagement,
        $dateFormat = 'M j, Y H:i:s A',
        array $data = [])
    {
        parent::__construct($filter, $localeDate, $localeResolver, $dateFormat, $data);
        $this->_bookmarkManagement = $bookmarkManagement;
    }

    protected function getActiveColumns($component){
        $bookmark = $this->_bookmarkManagement->getByIdentifierNamespace('current', $component->getName());

        $config = $bookmark->getConfig();
        $columns = $config['current']['columns'];
        $_activeColumns = [];
        foreach ($columns as $column => $config){
            if(true === $config['visible'] && $column != 'ids'){
                $_activeColumns[] = $column;
            }
        }
        return $_activeColumns;
    }
    /**
     * @param UiComponentInterface $component
     * @return UiComponentInterface[]
     * @throws \Exception
     */
    protected function getColumns(UiComponentInterface $component)
    {
        if (!isset($this->columns[$component->getName()])) {

            $activeColumns = $this->getActiveColumns($component);

            $columns = $this->getColumnsComponent($component);
            foreach ($columns->getChildComponents() as $column) {
                if ($column->getData('config/label') && $column->getData('config/dataType') !== 'actions') {
                    if(in_array($column->getName(), $activeColumns)) {
                        $this->columns[$component->getName()][$column->getName()] = $column;
                    }
                }
            }
        }
        return $this->columns[$component->getName()];
    }
}

Done.

Let enjoy your module.

Next Post: Add total at bottom grid report on admin.

Please follow and like us:
error

Leave a Reply

Your email address will not be published.

Follow by Email
Facebook
Facebook
LinkedIn