/   /   /  Magento 2 programming : implement import with (import.xml)

Note:

For more extensions and themes visit our store

Magento 2 programming : implement import with (import.xml)


Magento 2 import export module give you the ability to implement it behavior(standard system export import)  with simple xml and general adapter . Some point before stated :
A – For import you need create import.xml inside etc of your module
B : You can create just import without export
C : Standard place to show of your  import module is form menu system→export or system→ import .

Download simple project from github

In this course we try to create our custom module for import customer group with class tax id ,
the table customer_group have 3 column customer_group_id,customer_group_code,tax_class_id ,
ou customer_group.csv will be like :
customer_group_code,tax_class_id
new group1,3
new group2,4
………………….

1 -  Implement import.xml:

First for all you need create import.xml inside etc folder in your module (Example module Ibnab/Tutie)
etc/import.xml :

  1.  
  2. <?xml version="1.0"?>
  3. <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_ImportExport:etc/import.xsd">
  4.     <entity name="customer_group" label="Customer Group" model="Ibnab\Tutie\Model\Import\CustomerGroup" behaviorModel="Magento\ImportExport\Model\Source\Import\Behavior\Basic" />
  5. </config>
  6.  

now if you from menu to system→ import you will finding input select (with label Entity Type
) you will find as option added Entity Type but before using you need create your model adapter (Ibnab\Tutie\Model\Import\CustomerGroup) with second step.
1 -  Create your model adapter:
Inside folder Model create folder Import and inside it create class CustomerGroup.php and fill :
  1.  
  2. <?php
  3. namespace Ibnab\Tutie\Model\Import;
  4. use Ibnab\Tutie\Model\Import\CustomerGroup\RowValidatorInterface as ValidatorInterface;
  5. use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface;
  6. class CustomerGroup extends \Magento\ImportExport\Model\Import\Entity\AbstractEntity
  7. {
  8.     const TITLE = 'customer_group_code';
  9.     const TAX = 'tax_class_id';
  10.     const TABLE_Entity = 'customer_group';
  11.     /**
  12.      * Validation failure message template definitions
  13.      *
  14.      * @var array
  15.      */
  16.     protected $_messageTemplates = [
  17.         ValidatorInterface::ERROR_TITLE_IS_EMPTY => 'TITLE is empty',
  18.     ];
  19.      protected $_permanentAttributes = [self::TITLE];
  20.     /**
  21.      * If we should check column names
  22.      *
  23.      * @var bool
  24.      */
  25.     protected $needColumnCheck = true;
  26.     protected $groupFactory;
  27.     /**
  28.      * Valid column names
  29.      *
  30.      * @array
  31.      */
  32.     protected $validColumnNames = [
  33.         self::TITLE,
  34.         self::TAX,
  35.     ];
  36.     /**
  37.      * Need to log in import history
  38.      *
  39.      * @var bool
  40.      */
  41.     protected $logInHistory = true;
  42.     protected $_validators = [];
  43.     /**
  44.      * @var \Magento\Framework\Stdlib\DateTime\DateTime
  45.      */
  46.     protected $_connection;
  47.     protected $_resource;
  48.     /**
  49.      * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  50.      */
  51.     public function __construct(
  52.         \Magento\Framework\Json\Helper\Data $jsonHelper,
  53.         \Magento\ImportExport\Helper\Data $importExportData,
  54.         \Magento\ImportExport\Model\ResourceModel\Import\Data $importData,
  55.         \Magento\Framework\App\ResourceConnection $resource,
  56.         \Magento\ImportExport\Model\ResourceModel\Helper $resourceHelper,
  57.         \Magento\Framework\Stdlib\StringUtils $string,
  58.         ProcessingErrorAggregatorInterface $errorAggregator,
  59.         \Magento\Customer\Model\GroupFactory $groupFactory
  60.     ) {
  61.         $this->jsonHelper = $jsonHelper;
  62.         $this->_importExportData = $importExportData;
  63.         $this->_resourceHelper = $resourceHelper;
  64.         $this->_dataSourceModel = $importData;
  65.         $this->_resource = $resource;
  66.         $this->_connection = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);
  67.         $this->errorAggregator = $errorAggregator;
  68.         $this->groupFactory = $groupFactory;
  69.     }
  70.     /**
  71.      * Entity type code getter.
  72.      *
  73.      * @return string
  74.      */
  75.     public function getEntityTypeCode()
  76.     {
  77.         return 'customer_group';
  78.     }
  79.     /**
  80.      * Row validation.
  81.      *
  82.      * @param array $rowData
  83.      * @param int $rowNum
  84.      * @return bool
  85.      */
  86.     public function validateRow(array $rowData, $rowNum)
  87.     {
  88.         $title = false;
  89.         if (isset($this->_validatedRows[$rowNum])) {
  90.             return !$this->getErrorAggregator()->isRowInvalid($rowNum);
  91.         }
  92.         $this->_validatedRows[$rowNum] = true;
  93.         // BEHAVIOR_DELETE use specific validation logic
  94.        // if (\Magento\ImportExport\Model\Import::BEHAVIOR_DELETE == $this->getBehavior()) {
  95.             if (!isset($rowData[self::TITLE]) || empty($rowData[self::TITLE])) {
  96.                 $this->addRowError(ValidatorInterface::ERROR_TITLE_IS_EMPTY, $rowNum);
  97.                 return false;
  98.             }
  99.         return !$this->getErrorAggregator()->isRowInvalid($rowNum);
  100.     }
  101.     /**
  102.      * Create Advanced price data from raw data.
  103.      *
  104.      * @throws \Exception
  105.      * @return bool Result of operation.
  106.      */
  107.     protected function _importData()
  108.     {
  109.         if (\Magento\ImportExport\Model\Import::BEHAVIOR_DELETE == $this->getBehavior()) {
  110.             $this->deleteEntity();
  111.         } elseif (\Magento\ImportExport\Model\Import::BEHAVIOR_REPLACE == $this->getBehavior()) {
  112.             $this->replaceEntity();
  113.         } elseif (\Magento\ImportExport\Model\Import::BEHAVIOR_APPEND == $this->getBehavior()) {
  114.             $this->saveEntity();
  115.         }
  116.         return true;
  117.     }
  118.     /**
  119.      * Save newsletter subscriber
  120.      *
  121.      * @return $this
  122.      */
  123.     public function saveEntity()
  124.     {
  125.         $this->saveAndReplaceEntity();
  126.         return $this;
  127.     }
  128.     /**
  129.      * Replace newsletter subscriber
  130.      *
  131.      * @return $this
  132.      */
  133.     public function replaceEntity()
  134.     {
  135.         $this->saveAndReplaceEntity();
  136.         return $this;
  137.     }
  138.     /**
  139.      * Deletes newsletter subscriber data from raw data.
  140.      *
  141.      * @return $this
  142.      */
  143.     public function deleteEntity()
  144.     {
  145.         $listTitle = [];
  146.         while ($bunch = $this->_dataSourceModel->getNextBunch()) {
  147.             foreach ($bunch as $rowNum => $rowData) {
  148.                 $this->validateRow($rowData, $rowNum);
  149.                 if (!$this->getErrorAggregator()->isRowInvalid($rowNum)) {
  150.                     $rowTtile = $rowData[self::TITLE];
  151.                     $listTitle[] = $rowTtile;
  152.                 }
  153.                 if ($this->getErrorAggregator()->hasToBeTerminated()) {
  154.                     $this->getErrorAggregator()->addRowToSkip($rowNum);
  155.                 }
  156.             }
  157.         }
  158.         if ($listTitle) {
  159.             $this->deleteEntityFinish(array_unique($listTitle),self::TABLE_Entity);
  160.         }
  161.         return $this;
  162.     }
  163.  /**
  164.      * Save and replace newsletter subscriber
  165.      *
  166.      * @return $this
  167.      * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  168.      * @SuppressWarnings(PHPMD.NPathComplexity)
  169.      */
  170.     protected function saveAndReplaceEntity()
  171.     {
  172.         $behavior = $this->getBehavior();
  173.         $listTitle = [];
  174.         while ($bunch = $this->_dataSourceModel->getNextBunch()) {
  175.             $entityList = [];
  176.             foreach ($bunch as $rowNum => $rowData) {
  177.                 if (!$this->validateRow($rowData, $rowNum)) {
  178.                     $this->addRowError(ValidatorInterface::ERROR_TITLE_IS_EMPTY, $rowNum);
  179.                     continue;
  180.                 }
  181.                 if ($this->getErrorAggregator()->hasToBeTerminated()) {
  182.                     $this->getErrorAggregator()->addRowToSkip($rowNum);
  183.                     continue;
  184.                 }
  185.                 $rowTtile= $rowData[self::TITLE];
  186.                 $listTitle[] = $rowTtile;
  187.                 $entityList[$rowTtile][] = [
  188.                   self::TITLE => $rowData[self::TITLE],
  189.                   self::TAX => $rowData[self::TAX],
  190.                 ];
  191.             }
  192.             if (\Magento\ImportExport\Model\Import::BEHAVIOR_REPLACE == $behavior) {
  193.                 if ($listTitle) {
  194.                     if ($this->deleteEntityFinish(array_unique(  $listTitle), self::TABLE_Entity)) {
  195.                         $this->saveEntityFinish($entityList, self::TABLE_Entity);
  196.                     }
  197.                 }
  198.             } elseif (\Magento\ImportExport\Model\Import::BEHAVIOR_APPEND == $behavior) {
  199.                 $this->saveEntityFinish($entityList, self::TABLE_Entity);
  200.             }
  201.         }
  202.         return $this;
  203.     }
  204.     /**
  205.      * Save product prices.
  206.      *
  207.      * @param array $priceData
  208.      * @param string $table
  209.      * @return $this
  210.      */
  211.     protected function saveEntityFinish(array $entityData, $table)
  212.     {
  213.         if ($entityData) {
  214.             $tableName = $this->_connection->getTableName($table);
  215.             $entityIn = [];
  216.             foreach ($entityData as $id => $entityRows) {
  217.                     foreach ($entityRows as $row) {
  218.                         $entityIn[] = $row;
  219.                     }
  220.             }
  221.             if ($entityIn) {
  222.                 $this->_connection->insertOnDuplicate($tableName, $entityIn,[
  223.                 self::TITLE,
  224.                 self::TAX
  225.             ]);
  226.             }
  227.         }
  228.         return $this;
  229.     }
  230.     protected function deleteEntityFinish(array $listTitle, $table)
  231.     {
  232.         if ($table && $listTitle) {
  233.                 try {
  234.                     $this->countItemsDeleted += $this->_connection->delete(
  235.                         $this->_connection->getTableName($table),
  236.                         $this->_connection->quoteInto('customer_group_code IN (?)', $listTitle)
  237.                     );
  238.                     return true;
  239.                 } catch (\Exception $e) {
  240.                     return false;
  241.                 }
  242.       } else {
  243.             return false;
  244.         }
  245.     }
  246. }
  247.  

Some important technical explains:

  1.  
  2.  const TITLE = 'customer_group_code';
  3.  const TAX = 'tax_class_id';
  4.  const TABLE_Entity = 'customer_group';
  5.  

here we declare or constants columns and  TABLE_Entity  form where we deleting and inserting .
   

  1.  
  2.         protected $validColumnNames = [
  3.         self::TITLE,
  4.         self::TAX,
  5.     ];
  6.  

is check the system check if the header of csv is like this or no in  validColumnNames or no .
   
  1.  
  2.     public function getEntityTypeCode()
  3.     {
  4.         return 'customer_group';
  5.     }
  6.  

return the same code inside your import.xml name="customer_group" .

   

  1.  
  2.      public function validateRow(array $rowData, $rowNum)
  3.     {
  4.         $title = false;
  5.         if (isset($this->_validatedRows[$rowNum])) {
  6.             return !$this->getErrorAggregator()->isRowInvalid($rowNum);
  7.         }
  8.         $this->_validatedRows[$rowNum] = true;
  9.         // BEHAVIOR_DELETE use specific validation logic
  10.        // if (\Magento\ImportExport\Model\Import::BEHAVIOR_DELETE == $this->getBehavior()) {
  11.             if (!isset($rowData[self::TITLE]) || empty($rowData[self::TITLE])) {
  12.                 $this->addRowError(ValidatorInterface::ERROR_TITLE_IS_EMPTY, $rowNum);
  13.                 return false;
  14.             }
  15.         return !$this->getErrorAggregator()->isRowInvalid($rowNum);
  16.     }
  17.  

we validate the current row with this line here just simple test if is empty .
 The rest functions is implemented for insert  update and delete.

Don't forget to add our Ibnab\Tutie\Model\Import\CustomerGroup\RowValidatorInterfac  as ValidatorInterface used inside function validateRow and fill it with :

  1.  
  2. <?php
  3. /**
  4.  * Copyright © 2015 Magento. All rights reserved.
  5.  * See COPYING.txt for license details.
  6.  */
  7. namespace Ibnab\Tutie\Model\Import\CustomerGroup;
  8. interface RowValidatorInterface extends \Magento\Framework\Validator\ValidatorInterface
  9. {
  10.   const ERROR_INVALID_TITLE= 'InvalidValueTITLE';
  11.        const ERROR_TITLE_IS_EMPTY = 'EmptyTITLE';
  12.     /**
  13.      * Initialize validator
  14.      *
  15.      * @return $this
  16.      */
  17.     public function init($context);
  18. }
  19.  

Comments

Related Posts

make your store more efficient

Solving problems. With open source technology. Professional results. That’s what makes Ibnab your best choice

IBNAB is a company made of a group of professionals whose work is providing secure open source solutions. Our company strives for reaching magnificent results with each experience and provides professional open source solutions that cover every part of the business process.