I have been searching for a way of achieving this but so far no luck. I have also looked through the core and found where it is called (vendor\magento\module-import-export\Controller\Adminhtml\Import\Start.php
) but can't work out where to define the CSV file to import.
I know I need to pass data to it like so:
Array
(
[form_key] => 123456789xyz
[entity] => catalog_product
[behavior] => append
[validation_strategy] => validation-stop-on-errors
[allowed_error_count] => 10
[_import_field_separator] => ,
[_import_multiple_value_separator] => ,
[import_images_file_dir] =>
)
Any one have any hints as to how I can run the native CSV import via code?
Thanks
Best Answer
\Magento\ImportExport\Model\Export\Adapter\CsvFactory
into your constructorCsvFactory
, you need to create an instance of the CSV Model:$csvModel = $this->csvFactory->create(['destination' => 'path/to/your/file.csv']);
$csvModel->writeRow(['your' => 'data']);
\Magento\ImportExport\Model\ImportFactory
into your constructorImportFactory
, you need to instantiate the Import Model:$importModel = $this->importModelFactory->create();
$importModel->setData(['your' => 'data']);
$sourceModel = ImportAdapter::findAdapterFor( 'path/to/your/file.csv', $this->filesystem->getDirectoryWrite(DirectoryList::ROOT), $importModel->getData('_import_field_separator') );
$isValid = $importModel->validateSource($sourceModel);
if ($importModel->getProcessedRowsCount() === 0 || !$isValid || $importModel->getErrorAggregator()->getErrorsCount()) { // Display or log the error return; }
$importModel->importSource();
There's a lot more involved in the error handling, but this should at least get you started.