MAGENTO 2:如何将CSV文件导入自定义表?

今天,我们将讨论如何在Magento 2中将csv文件导入到自定义表中。我们对Magento 2产品的货架期延长具有类似的要求,我们必须允许管理员加载库存针对不同产品批次的有效期。

像往常一样,让我们​​继续逐步实施以实现Magento 2如何将CSV文件导入自定义表格-:

步骤1 – 在app / code / Scommerce / Custom / etc中创建文件import.xml

<?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="Scommerce\Custom\Model\Import\CustomImport" behaviorModel="Magento\ImportExport\Model\Source\Import\Behavior\Basic" />
</config>

name:下拉值的名称

label:下拉选项的标签名称

model:将负责处理导入逻辑的模型的类名

behaviorModel:Magento Basic导入行为模型类的类名称

第2步 – 在app / code / Scommerce / Custom / Model / Import文件夹下创建文件CustomImport.php

<?php namespace Scommerce\Custom\Model\Import; use Scommerce\Custom\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];
    /**
     * If we should check column names
     *
     * @var bool
     */
    protected $needColumnCheck = true;
    protected $groupFactory;
    /**
     * Valid column names
     *
     * @array
     */
    protected $validColumnNames = [
    self::ID,
    self::NAME,
    self::DESC,
    ];
 
    /**
     * Need to log in import history
     *
     * @var bool
     */
    protected $logInHistory = true;
 
    protected $_validators = [];
 
 
    /**
     * @var \Magento\Framework\Stdlib\DateTime\DateTime
     */
    protected $_connection;
    protected $_resource;
 
    /**
     * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
     */
    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;
    }
 
    /**
     * Entity type code getter.
     *
     * @return string
     */
    public function getEntityTypeCode()
    {
      return 'custom_import';
    }
 
    /**
     * Row validation.
     *
     * @param array $rowData
     * @param int $rowNum
     * @return bool
     */
    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);
    }
 
   /**
     * Create Advanced message data from raw data.
     *
     * @throws \Exception
     * @return bool Result of operation.
     */
    protected function _importData()
    {
        $this->saveEntity();
        return true;
    }
    /**
     * Save entity
     *
     * @return $this
     */
    public function saveEntity()
    {
        $this->saveAndReplaceEntity();
        return $this;
    }
 
    /**
     * Replace entity data
     *
     * @return $this
     */
    public function replaceEntity()
    {
       $this->saveAndReplaceEntity();
       return $this;
    }
    /**
     * Deletes entity data from raw data.
     *
     * @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;
    }
     
    /**
     * Save and replace entity
     *
     * @return $this
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    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;
    }
 
    /**
     * Save custom data.
     *
     * @param array $entityData
     * @param string $table
     * @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;
    }
 
     /**
     * Delete custom data.
     *
     * @param array $entityData
     * @param string $table
     * @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;
      }
    }
}

步骤3 – 在app / code / Scommerce / Custom / Model / Import / CustomImport文件夹下创建验证器接口文件RowValidatorInterface.php

<?php
namespace Scommerce\Custom\Model\Import\CustomImport;
interface RowValidatorInterface extends \Magento\Framework\Validator\ValidatorInterface
{
       const ERROR_INVALID_TITLE= 'InvalidValueTITLE';
       const ERROR_MESSAGE_IS_EMPTY = 'EmptyMessage';
    /**
     * Initialize validator
     *
     * @return $this
     */
    public function init($context);
}

步骤4 – 使用以下列创建名为custom_table的自定义表
ID
Title
Description

步骤5 –使用以下列创建CSV文件,并在Magento 2管理员->系统->数据传输->导入->从下拉列表中选择“自定义数据导入”

  • ID
  • Title
  • Description

希望本文对您有所帮助。请留下您的评论,让我们知道您的想法?谢谢。

版权属于: sbboke版权所有。

转载时必须以链接形式注明作者和原始出处及本声明。

张贴在magento2教程标签:

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
最旧
最新 最多投票
内联反馈
查看所有评论