5

I created a custom import module from two custom models and tables. The imports works fine, and without any error or problem now. But I noticed that next to Entity Type dropdown, appears a "Dowload Sample File".

enter image description here

And, when I click in that (when is selected my custom entity type), the page show me a "There is no sample file for this entity." error.

So, after check the file vendor/magento/module-import-export/Controller/Adminhtml/Import/Download.php it's look like Magento is searching the sample file in the directory:

vendor/magento/module-import-export/Files/Sample

So, the "quick" way of correcting this problem, I suppose, is to add the files of my modules in that directory. However, my question is: is this "right"? My logic tells me that it's not good to touch ANYTHING that's in the vendor folder. But then, what is the other alternative that could apply?, since it seems that with these lines:

fileName = $this->getRequest()->getParam('filename') . '.csv';
$moduleDir = $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, self::SAMPLE_FILES_MODULE);
$fileAbsolutePath = $moduleDir . '/Files/Sample/' . $fileName;
$directoryRead = $this->readFactory->create($moduleDir);
$filePath = $directoryRead->getRelativePath($fileAbsolutePath);

Force to search directly in that directory.

Some suggestions?

1

4 Answers 4

10

I find some solution. Create one preference for overrides download file.

Add this code to di.xml file

<preference for="Magento\ImportExport\Controller\Adminhtml\Import\Download" type="NameSpace\ModuleName\Controller\Adminhtml\Import\Download"/>

Create directory with csv file

NameSpace/ModuleName/view/adminhtml/Files/Sample/your_csv_file.csv

Create Download.php file at NameSpace\ModuleName\Controller\Adminhtml\Import

And put this code

<?php

namespace NameSpace\ModuleName\Controller\Adminhtml\Import;

use Magento\Framework\Component\ComponentRegistrar;
use Magento\ImportExport\Controller\Adminhtml\Import as ImportController;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\ImportExport\Controller\Adminhtml\Import\Download as Mdownload;

class Download extends Mdownload
{
    protected $moduleReader;
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
        \Magento\Framework\Filesystem\Directory\ReadFactory $readFactory,
        \Magento\Framework\Component\ComponentRegistrar $componentRegistrar,
        \Magento\Framework\Module\Dir\Reader $moduleReader
    ) {
        parent::__construct(
            $context,
            $fileFactory,
            $resultRawFactory,
            $readFactory,
            $componentRegistrar

        );
        $this->moduleReader = $moduleReader;
    }
    public function getDirectory()
    {
        $viewDir = $this->moduleReader->getModuleDir(
            \Magento\Framework\Module\Dir::MODULE_VIEW_DIR,
            'NameSpace_ModuleName'
        );
        return $viewDir . '/adminhtml/Files/Sample/';
    }

    /**
     * Download sample file action
     *
     * @return \Magento\Framework\Controller\Result\Raw
     */
    public function execute()
    {
        $fileName = $this->getRequest()->getParam('filename') . '.csv';
        $moduleDir = $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, self::SAMPLE_FILES_MODULE);
        $fileAbsolutePath = $moduleDir . '/Files/Sample/' . $fileName;
        $directoryRead = $this->readFactory->create($moduleDir);
        $filePath = $directoryRead->getRelativePath($fileAbsolutePath);

        if (!$directoryRead->isFile($filePath)) {

            $fileAbsolutePath = $this->getDirectory() . $fileName;
            $directoryRead = $this->readFactory->create($this->getDirectory());
            $filePath = $directoryRead->getRelativePath($fileAbsolutePath);
            if (!$directoryRead->isFile($filePath)) {
            /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
                $this->messageManager->addError(__('There is no sample file for this entity.'));
                $resultRedirect = $this->resultRedirectFactory->create();
                $resultRedirect->setPath('*/import');
                return $resultRedirect;
            }
        }

        $fileSize = isset($directoryRead->stat($filePath)['size'])
            ? $directoryRead->stat($filePath)['size'] : null;

        $this->fileFactory->create(
            $fileName,
            null,
            DirectoryList::VAR_DIR,
            'application/octet-stream',
            $fileSize
        );
        /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
        $resultRaw = $this->resultRawFactory->create();
        $resultRaw->setContents($directoryRead->readFile($filePath));
        return $resultRaw;
    }
}

thats it, for any clarity related to this answer please mention in comment.

1
  • Thanks . This worked for me
    – Singhe
    Jul 15, 2021 at 11:15
7

For 2.3.x refer this blog link

Create plugin for sample download csv.

Create directory with csv file

NameSpace/ModuleName/Files/Sample/namespace_modulename.csv

Add this code to etc/adminhtml/di.xml file

<type name="Magento\ImportExport\Controller\Adminhtml\Import\Download">
    <plugin name="Namespace_ModuleName::Import" type="Namespace\ModuleName\Plugin\Import\Download" />
</type>

Create Download.php file at NameSpace\ModuleName\Plugin\Import\Download.php

And put this code

<?php
namespace Namespace\ModuleName\Plugin\Import; 

use Magento\Framework\App\Filesystem\DirectoryList;

class Download
{
    /**
        * @var \Magento\Framework\Module\Dir\Reader
        */
    private $reader;
    /**
        * @var \Magento\Framework\Filesystem\Directory\ReadFactory
        */
    private $readFactory;
    /**
        * @var \Magento\Framework\Message\ManagerInterface
        */
    private $messageManager;
    /**
        * @var \Magento\Framework\Controller\Result\RedirectFactory
        */
    private $resultRedirectFactory;
    /**
        * @var \Magento\Framework\App\Response\Http\FileFactory
        */
    private $fileFactory;
    /**
        * @var \Magento\Framework\Controller\Result\RawFactory
        */
    private $resultRawFactory;
    /**
        * @var \Magento\Framework\App\RequestInterface
        */
    private $requestInterface;

    public function __construct(
        \Magento\Framework\App\RequestInterface $requestInterface,
        \Magento\Framework\Module\Dir\Reader $reader,
        \Magento\Framework\Filesystem\Directory\ReadFactory $readFactory,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\Controller\Result\RawFactory $resultRawFactory
    ) {

        $this->reader = $reader;
        $this->readFactory = $readFactory;
        $this->messageManager = $messageManager;
        $this->resultRedirectFactory = $resultRedirectFactory;
        $this->fileFactory = $fileFactory;
        $this->resultRawFactory = $resultRawFactory;
        $this->requestInterface = $requestInterface;
    }

    public function afterExecute(
        $subject,
        $result
    ) {
        if ($this->requestInterface->getParam('filename') == 'namespace_modulename_profiler') {
            $fileName = $this->requestInterface->getParam('filename') . '.csv';
            $moduleDir = $this->reader->getModuleDir('', 'Namespace_ModuleName');;
            $fileAbsolutePath = $moduleDir . '/Files/Sample/' . $fileName;
            $directoryRead = $this->readFactory->create($moduleDir);
            $filePath = $directoryRead->getRelativePath($fileAbsolutePath);

            if (!$directoryRead->isFile($filePath)) {
                /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
                $this->messageManager->addError(__('There is no sample file for this entity.'));
                $resultRedirect = $this->resultRedirectFactory->create();
                $resultRedirect->setPath('*/import');
                return $resultRedirect;
            } else {
                $this->messageManager->getMessages(true);
            }

            $fileSize = isset($directoryRead->stat($filePath)['size'])
                ? $directoryRead->stat($filePath)['size'] : null;

            $this->fileFactory->create(
                $fileName,
                null,
                DirectoryList::VAR_DIR,
                'application/octet-stream',
                $fileSize
            );

            /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
            $resultRaw = $this->resultRawFactory->create();
            $resultRaw->setContents($directoryRead->readFile($filePath));
            return $resultRaw;
        }

        return $result;
    }
}

For any clarity related to this answer please mention in comment.

6
  • Awesome @ronak Patel solution working excellent. Jan 4, 2020 at 19:08
  • @NagarajuK, Ronk Patel, what should be the subject, in after excute is that Controller File are any Arguments to be passed. Mar 31, 2020 at 11:50
  • Magento\ImportExport\Controller\Adminhtml\Import\Download is the subject Mar 31, 2020 at 12:04
  • @NagarajuK thanks For your Help. Mar 31, 2020 at 12:06
  • @Learing_Coder firebearstudio.com/blog/… Mar 31, 2020 at 16:09
2

In Magento 2.3 onwards, the sample file can be specified from custom module's di.xml file as below:

<type name="Magento\ImportExport\Model\Import\SampleFileProvider">
        <arguments>
            <argument name="samples" xsi:type="array">
                <item name="custom_import_entity" xsi:type="string">Namespace_ModuleName</item>
            </argument>
        </arguments>
    </type>

Here item name custom_import_entity should be similar to the entity name defined in Namespace/ModuleName/etc/export.xml file as in the below example.

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_ImportExport:etc/export.xsd">
    <entity name="custom_import_entity" label="Products" model="Magento\CatalogImportExport\Model\Export\Product" entityAttributeFilterType="catalog_product"/>
    <entityType entity="custom_import_entity" name="simple" model="Magento\CatalogImportExport\Model\Export\Product\Type\Simple" />
    <entityType entity="custom_import_entity" name="virtual" model="Magento\CatalogImportExport\Model\Export\Product\Type\Simple" />
    <fileFormat name="csv" label="CSV" model="Magento\ImportExport\Model\Export\Adapter\Csv" />
</config>

Also, make sure to add the below method in your export entity model class specified in the export.xml file above.

/**
     * EAV entity type code getter.
     *
     * @return string
     */
    public function getEntityTypeCode()
    {
        return 'custom_import_entity';
    }

Sample CSV file path: Namespace/ModuleName/Files/Sample/custom_import_entity.csv

0

app/code/VendoreName/CustomDataImport/etc

db_schema.xml

<?xml version="1.0"?>

<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="custom_import">
        <column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" comment="Entity Id" identity="true" />
        <column xsi:type="varchar" name="name" nullable="false" length="255" comment="Product Name"/>
        <column xsi:type="int" name="duration" padding="10" unsigned="true" nullable="false" comment="Duration"/>
        <constraint xsi:type="primary" referenceId="CUSTOM_IMPORT_ID_PRIMARY">
            <column name="entity_id"/>
        </constraint>
    </table>
</schema>

enter image description here

app/code/VendoreName/CustomDataImport/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="VendoreName\CustomDataImport\Model\Import\CustomImport" behaviorModel="Magento\ImportExport\Model\Source\Import\Behavior\Basic" />
</config>

app/code/VendoreName/CustomDataImport/Files/Sample

custom_import.csv

entity_id,name,duration
,"Name 1",90
2,"Name 3",120

app/code/VendoreName/CustomDataImport/etc

di.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <type name="Magento\ImportExport\Model\Import\SampleFileProvider">
        <arguments>
            <argument name="samples" xsi:type="array">
                <item name="custom_import" xsi:type="string">VendoreName_CustomDataImport</item>
            </argument>
        </arguments>
    </type>

</config>

app/code/VendoreName/CustomDataImport/Model/Import

CustomImport.php

<?php

namespace VendoreName\CustomDataImport\Model\Import;

use Exception;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\Json\Helper\Data as JsonHelper;
use Magento\ImportExport\Helper\Data as ImportHelper;
use Magento\ImportExport\Model\Import;
use Magento\ImportExport\Model\Import\Entity\AbstractEntity;
use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface;
use Magento\ImportExport\Model\ResourceModel\Helper;
use Magento\ImportExport\Model\ResourceModel\Import\Data;

/**
 * Class Courses
 */
class CustomImport extends AbstractEntity
{
    const ENTITY_CODE = 'custom_import';
    const TABLE = 'custom_import';
    const ENTITY_ID_COLUMN = 'entity_id';

    /**
     * If we should check column names
     */
    protected $needColumnCheck = true;

    /**
     * Need to log in import history
     */
    protected $logInHistory = true;

    /**
     * Permanent entity columns.
     */
    protected $_permanentAttributes = [
        'entity_id',
    ];

    /**
     * Valid column names
     */
    protected $validColumnNames = [
        'entity_id',
        'name',
        'duration',
    ];

    /**
     * @var AdapterInterface
     */
    protected $connection;

    /**
     * @var ResourceConnection
     */
    private $resource;

    /**
     * Courses constructor.
     *
     * @param JsonHelper $jsonHelper
     * @param ImportHelper $importExportData
     * @param Data $importData
     * @param ResourceConnection $resource
     * @param Helper $resourceHelper
     * @param ProcessingErrorAggregatorInterface $errorAggregator
     */
    public function __construct(
        JsonHelper $jsonHelper,
        ImportHelper $importExportData,
        Data $importData,
        ResourceConnection $resource,
        Helper $resourceHelper,
        ProcessingErrorAggregatorInterface $errorAggregator
    ) {
        $this->jsonHelper = $jsonHelper;
        $this->_importExportData = $importExportData;
        $this->_resourceHelper = $resourceHelper;
        $this->_dataSourceModel = $importData;
        $this->resource = $resource;
        $this->connection = $resource->getConnection(ResourceConnection::DEFAULT_CONNECTION);
        $this->errorAggregator = $errorAggregator;
        $this->initMessageTemplates();
    }

    /**
     * Entity type code getter.
     *
     * @return string
     */
    public function getEntityTypeCode()
    {
        return static::ENTITY_CODE;
    }

    /**
     * Get available columns
     *
     * @return array
     */
    public function getValidColumnNames(): array
    {
        return $this->validColumnNames;
    }

    /**
     * Row validation
     *
     * @param array $rowData
     * @param int $rowNum
     *
     * @return bool
     */
    public function validateRow(array $rowData, $rowNum): bool
    {
        $name = $rowData['name'] ?? '';
        $duration = (int) $rowData['duration'] ?? 0;

        if (!$name) {
            $this->addRowError('NameIsRequired', $rowNum);
        }

        if (!$duration) {
            $this->addRowError('DurationIsRequired', $rowNum);
        }

        if (isset($this->_validatedRows[$rowNum])) {
            return !$this->getErrorAggregator()->isRowInvalid($rowNum);
        }

        $this->_validatedRows[$rowNum] = true;

        return !$this->getErrorAggregator()->isRowInvalid($rowNum);
    }

    /**
     * Init Error Messages
     */
    private function initMessageTemplates()
    {
        $this->addMessageTemplate(
            'NameIsRequired',
            __('The name cannot be empty.')
        );
        $this->addMessageTemplate(
            'DurationIsRequired',
            __('Duration should be greater than 0.')
        );
    }

    /**
     * Import data
     *
     * @return bool
     *
     * @throws Exception
     */
    protected function _importData(): bool
    {
        switch ($this->getBehavior()) {
            case Import::BEHAVIOR_DELETE:
                $this->deleteEntity();
                break;
            case Import::BEHAVIOR_REPLACE:
                $this->saveAndReplaceEntity();
                break;
            case Import::BEHAVIOR_APPEND:
                $this->saveAndReplaceEntity();
                break;
        }

        return true;
    }

    /**
     * Delete entities
     *
     * @return bool
     */
    private function deleteEntity(): bool
    {
        $rows = [];
        while ($bunch = $this->_dataSourceModel->getNextBunch()) {
            foreach ($bunch as $rowNum => $rowData) {
                $this->validateRow($rowData, $rowNum);

                if (!$this->getErrorAggregator()->isRowInvalid($rowNum)) {
                    $rowId = $rowData[static::ENTITY_ID_COLUMN];
                    $rows[] = $rowId;
                }

                if ($this->getErrorAggregator()->hasToBeTerminated()) {
                    $this->getErrorAggregator()->addRowToSkip($rowNum);
                }
            }
        }

        if ($rows) {
            return $this->deleteEntityFinish(array_unique($rows));
        }

        return false;
    }

    /**
     * Save and replace entities
     *
     * @return void
     */
    private function saveAndReplaceEntity()
    {
        $behavior = $this->getBehavior();
        $rows = [];
        while ($bunch = $this->_dataSourceModel->getNextBunch()) {
            $entityList = [];

            foreach ($bunch as $rowNum => $row) {
                if (!$this->validateRow($row, $rowNum)) {
                    continue;
                }

                if ($this->getErrorAggregator()->hasToBeTerminated()) {
                    $this->getErrorAggregator()->addRowToSkip($rowNum);

                    continue;
                }

                $rowId = $row[static::ENTITY_ID_COLUMN];
                $rows[] = $rowId;
                $columnValues = [];

                foreach ($this->getAvailableColumns() as $columnKey) {
                    $columnValues[$columnKey] = $row[$columnKey];
                }

                $entityList[$rowId][] = $columnValues;
                $this->countItemsCreated += (int) !isset($row[static::ENTITY_ID_COLUMN]);
                $this->countItemsUpdated += (int) isset($row[static::ENTITY_ID_COLUMN]);
            }
            if (Import::BEHAVIOR_REPLACE === $behavior) {
                if ($rows && $this->deleteEntityFinish(array_unique($rows))) {
                    $this->saveEntityFinish($entityList);
                }
            } elseif (Import::BEHAVIOR_APPEND === $behavior) {
                $this->saveEntityFinish($entityList);
            }
        }
    }

    /**
     * Save entities
     *
     * @param array $entityData
     *
     * @return bool
     */
    private function saveEntityFinish(array $entityData): bool
    {
        if ($entityData) {
            $tableName = $this->connection->getTableName(static::TABLE);
            $rows = [];

            foreach ($entityData as $entityRows) {
                foreach ($entityRows as $row) {
                    $rows[] = $row;
                }
            }

            if ($rows) {
                $this->connection->insertOnDuplicate($tableName, $rows, $this->getAvailableColumns());

                return true;
            }

            return false;
        }
    }

    /**
     * Delete entities
     *
     * @param array $entityIds
     *
     * @return bool
     */
    private function deleteEntityFinish(array $entityIds): bool
    {
        if ($entityIds) {
            try {
                $this->countItemsDeleted += $this->connection->delete(
                    $this->connection->getTableName(static::TABLE),
                    $this->connection->quoteInto(static::ENTITY_ID_COLUMN . ' IN (?)', $entityIds)
                );

                return true;
            } catch (Exception $e) {
                return false;
            }
        }

        return false;
    }

    /**
     * Get available columns
     *
     * @return array
     */
    private function getAvailableColumns(): array
    {
        return $this->validColumnNames;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.