Exporting Selected Rows to CSV in Magento 2 Grid
I understand that you’re facing an issue while trying to export selected rows from your custom grid to a CSV file in Magento 2. Your current implementation is exporting all grid data instead of the specifically selected records. Let me guide you through this process step by step.
Understanding the Problem
The key lies in how Magento’s built-in grid system and the getCsv() method work. By default, getCsv() exports all visible rows, not just the selected ones. This is why your current implementation isn’t working as expected.
The Solution Approach
To solve this issue, we need to modify our approach in two main areas: the grid block and the export action class.
Step 1: Modify the Grid Block
In your Grid.php file, you’re already setting setSaveParametersInSession(true). This is a good start as it saves the current state of the grid (including selected rows) to the session. However, we need to use this information in our export action.
Step 2: Modify the Export Action Class
The main issue is in your execute() method of the ExportCsv class. Let’s update this method as follows:
public function execute()
{
$this->_view->loadLayout(false);
$fileName = self::FILENAME;
// Get selected rows from session
$selectedRows = $this->_session->getSelectedRows();
if (!$selectedRows) {
$this->messageManager->addError(__('No records selected.'));
return $this->resultRedirectFactory->create()->setPath('*/*/');
}
// Prepare the CSV content using only selected rows
$content = '';
foreach ($selectedRows as $row) {
$content .= implode(',', [
$row['registration_code'],
$row['url'],
// Add other column values here...
]) . "\n";
}
return $this->_fileFactory->create(
$fileName,
$content,
DirectoryList::VAR_DIR
);
}
Key Changes Explained
-
We first retrieve the selected rows from the session using
$_session->getSelectedRows(). This contains an array of the selected row data. -
We check if there are any selected rows. If not, we display an error message and redirect to the grid page.
-
Instead of calling
getCsv()on your custom grid block, you’re building the CSV content manually by iterating over the selected rows and adding each record to the$contentvariable. -
We use
implode(',', ...)to format each row as a CSV line with columns separated by commas. -
Finally, we return the file factory object with the updated CSV content.
Conclusion
By following these steps, you should now be able to export only the selected rows from your custom grid to a CSV file in Magento 2. This approach leverages Magento’s built-in grid system while allowing for more fine-grained control over the exported data.
Remember, always test changes thoroughly and backup your database before making significant modifications to your store codebase.
For more advanced customizations and best practices in Magento development, I recommend checking out the resources available at Laravel Company. They provide a wealth of guides and tutorials for Magento developers looking to improve their skills and stay up-to-date with the latest techniques.