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:
1 2 3 4 |
<?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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
<?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:
1 2 3 4 5 6 7 8 9 |
<?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’s working fine when add/update. but replace and delete functionality not working.
Hi
How to validate each row data in custom csv ?
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.
Now Working at all
It’s only loading custom import
It is not working. We can not find any custom Import in Entity Type field