3

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?

8

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.

4

I find best solution. 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.

  • Awesome @ronak Patel solution working excellent. – Nagaraju K Jan 4 at 19:08
0

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_name" xsi:type="string">Namespace_ModuleName</item>
            </argument>
        </arguments>
    </type>

Sample file path : Namespace/ModuleName/Files/Sample/custom_import_entity_name.csv

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.