I am facing an issue in My custom grid. I have added 'Export to CSV' in Grid and it is working fine.

Issue is I have added a row total in grid but in Exported CSV, total is actually the total of all rows rather then the total of filtered rows.

I am using a below code to add the Total row for a specific column. This code is working in Grid Block but not working in GridExport Block.

protected function _afterLoadCollection()
    $collection = $this->getCollection();

    $salesTotal = 0;

    foreach ($collection as $rowData) {
        $salesTotal += (float)$rowData->getPrice() * (float)$rowData->getQuantity();
    $this->setTotals(new \Magento\Framework\DataObject(
        array( 'subtotal'=>$salesTotal )
    return $this;

It seems that, _afterLoadCollection() never call in GridExport Block although both Blocks are extending the same class as

class Grid extends \Magento\Backend\Block\Widget\Grid\Extended { ... }
class GridExport extends \Magento\Backend\Block\Widget\Grid\Extended { ... }

Grid and CSV samples are attached for reference.

Grid enter image description here CSV enter image description here

1 Answer 1


I have resolved the issue. There are basically 2 functions in Extended Grid Block

namespace Magento\Backend\Block\Widget\Grid;
// other stuff
class Extended extends \Magento\Backend\Block\Widget\Grid implements \Magento\Backend\Block\Widget\Grid\ExportInterface
    // other code
    public function getCsvFile()
        // doesn't call _afterLoadCollection() function

    // other code
    public function getCsv()
         $csv = '';
         $this->_isExport = true;
         $this->_afterLoadCollection(); // That I needed
         // ...
     // ...

So I have used getCsv() function in my Controller as:

public function execute()
    $resultPage = $this->_resultPageFactory->create();

    $fileName = 'Referral_'. date('Y-m-d h:i:s') . '.csv';
    $exportBlock = $resultPage->getLayout()
    return $this->_fileFactory->create(
        $exportBlock->getCsv(), // this fucntion

Although, I am not sure what's the difference between getCsv() and getCsvFile()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.