Hello Magento Friends ?,
Today I am going to discuss How to Import CSV File to Custom Table In Magento 2. In case you skipped our previous blog, check it out here. How to Configure Flat Rate Shipping Method in Magento 2.
During the import of the product in Magento 2, some of the data or columns from the CSV file need to be imported to a custom table. So let’s crack up on the implementation to Import CSV file to Custom Table in Magento 2 ?
Steps to Import CSV File to Custom Table in Magento 2:
Step 1: Create an import.xml file at the following path:
app/code/Vendor/Extension/etc
Now, add the below code:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_ImportExport:etc/import.xsd"> <entity name="custom_import" label="Custom Import" model="Vendor\Extension\Model\Import\CustomImport" behaviorModel="Magento\ImportExport\Model\Source\Import\Behavior\Basic" /> </config>
Step 2: Create file CustomImport.php under app/code/Vendor/Extension/Model/Import folder and add the following code:
<?php namespace Vendor\Extension\Model\Import; use Vendor\Extension\Model\Import\CustomImport\RowValidatorInterface as ValidatorInterface; use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface; use Magento\Framework\App\ResourceConnection; class CustomImport extends \Magento\ImportExport\Model\Import\Entity\AbstractEntity { const ID = 'id'; const NAME = 'name'; const DESC = 'description'; const TABLE_Entity = 'custom_table'; /** * Validation failure message template definitions * * @var array */ protected $_messageTemplates = [ ValidatorInterface::ERROR_TITLE_IS_EMPTY => 'Name is empty',]; protected $_permanentAttributes = [self::ID]; protected $needColumnCheck = true; protected $groupFactory; protected $validColumnNames = [self::ID, self::NAME, self::DESC,]; protected $logInHistory = true; protected $_validators = []; protected $_connection; protected $_resource; public function __construct( \Magento\Framework\Json\Helper\Data $jsonHelper, \Magento\ImportExport\Helper\Data $importExportData, \Magento\ImportExport\Model\ResourceModel\Import\Data $importData, \Magento\Framework\App\ResourceConnection $resource, \Magento\ImportExport\Model\ResourceModel\Helper $resourceHelper, \Magento\Framework\Stdlib\StringUtils $string, ProcessingErrorAggregatorInterface $errorAggregator, \Magento\Customer\Model\GroupFactory $groupFactory) { $this->jsonHelper = $jsonHelper; $this->_importExportData = $importExportData; $this->_resourceHelper = $resourceHelper; $this->_dataSourceModel = $importData; $this->_resource = $resource; $this->_connection = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION); $this->errorAggregator = $errorAggregator; $this->groupFactory = $groupFactory; } public function getValidColumnNames() { return $this->validColumnNames; } public function getEntityTypeCode() { return 'custom_import'; } public function validateRow(array $rowData, $rowNum) { if (isset($this->_validatedRows[$rowNum])) { return !$this->getErrorAggregator()->isRowInvalid($rowNum); } $this->_validatedRows[$rowNum] = true; return !$this->getErrorAggregator()->isRowInvalid($rowNum); } protected function _importData() { $this->saveEntity(); return true; } public function saveEntity() { $this->saveAndReplaceEntity(); return $this; } public function replaceEntity() { $this->saveAndReplaceEntity(); return $this; } public function deleteEntity() { $listTitle = []; while ($bunch = $this->_dataSourceModel->getNextBunch()) { foreach ($bunch as $rowNum => $rowData) { $this->validateRow($rowData, $rowNum); if (!$this->getErrorAggregator()->isRowInvalid($rowNum)) { $rowTtile = $rowData[self::ID]; $listTitle[] = $rowTtile; } if ($this->getErrorAggregator()->hasToBeTerminated()) { $this->getErrorAggregator()->addRowToSkip($rowNum); } } } if ($listTitle) { $this->deleteEntityFinish(array_unique($listTitle),self::TABLE_Entity); } return $this; } protected function saveAndReplaceEntity() { $behavior = $this->getBehavior(); $listTitle = []; while ($bunch = $this->_dataSourceModel->getNextBunch()) { $entityList = []; foreach ($bunch as $rowNum => $rowData) { if (!$this->validateRow($rowData, $rowNum)) { $this->addRowError(ValidatorInterface::ERROR_TITLE_IS_EMPTY, $rowNum); continue; } if ($this->getErrorAggregator()->hasToBeTerminated()) { $this->getErrorAggregator()->addRowToSkip($rowNum); continue; } $rowTtile= $rowData[self::ID]; $listTitle[] = $rowTtile; $entityList[$rowTtile][] = [ self::ID => $rowData[self::ID], self::NAME => $rowData[self::NAME], self::DESC => $rowData[self::DESC],]; } if (\Magento\ImportExport\Model\Import::BEHAVIOR_REPLACE == $behavior) { if ($listTitle) { if ($this->deleteEntityFinish(array_unique( $listTitle), self::TABLE_Entity)) { $this->saveEntityFinish($entityList, self::TABLE_Entity); } } } elseif (\Magento\ImportExport\Model\Import::BEHAVIOR_APPEND == $behavior) { $this->saveEntityFinish($entityList, self::TABLE_Entity); } } return $this; } protected function saveEntityFinish(array $entityData, $table) { if ($entityData) { $tableName = $this->_connection->getTableName($table); $entityIn = []; foreach ($entityData as $id => $entityRows) { foreach ($entityRows as $row) { $entityIn[] = $row; } } if ($entityIn) { $this->_connection->insertOnDuplicate($tableName, $entityIn,[ self::ID, self::NAME, self::DESC]); } } return $this; } protected function deleteEntityFinish(array $ids, $table) { if ($table && $listTitle) { try { $this->countItemsDeleted += $this->_connection->delete( $this->_connection->getTableName($table), $this->_connection->quoteInto('id IN (?)', $ids)); return true; } catch (\Exception $e) { return false; } } else { return false; } } }
Step 3: Create validator interface file RowValidatorInterface.php under app/code/Vendor/Extension/Model/Import/CustomImport folder and add the below code:
<?php namespace Vendor\Extension\Model\Import\CustomImport; interface RowValidatorInterface extends \Magento\Framework\Validator\ValidatorInterface { const ERROR_INVALID_TITLE= 'InvalidValueTITLE'; const ERROR_MESSAGE_IS_EMPTY = 'EmptyMessage'; public function init($context); }
Step 4: Create custom_table with columns as ID, Title, and Description.
Step 5: Create CSV using the same columns in the admin panel. System > Data Transfer > Import. Select Custom Import in the Entity Type field.
Conclusion:
Hence, all have successfully implemented to import CSV file to a custom table in Magento 2. In case you face any difficulty while implementing the steps, let me know in the comment part below. Share the article with your friends.
Happy Reading ?
It is not working. We can not find any custom Import in Entity Type field
It’s only loading custom import
Now Working at all
In this case, we are creating the CSV and writing the data manually. It’s impossible when we work on large data. Is it possible without doing it manually? I need to loop through the row value which should be displayed in csv.
Hi
How to validate each row data in custom csv ?
it’s working fine when add/update. but replace and delete functionality not working.