1

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

migrated from stackoverflow.com Dec 2 '18 at 2:12

This question came from our site for professional and enthusiast programmers.

0

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->_prepareGrid();
         $this->getCollection()->getSelect()->limit();
         $this->getCollection()->setPageSize(0);
         $this->getCollection()->load();
         $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()
        ->createBlock(
            'Vendor\Module\Block\Adminhtml\Referrals\GridExport'
        );
    return $this->_fileFactory->create(
        $fileName,
        $exportBlock->getCsv(), // this fucntion
        DirectoryList::VAR_DIR
    );
}

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, privacy policy and cookie policy

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