Magento2 – Programmatically Run Native Product CSV Import

importmagento2

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

  1. You need to inject an instance of \Magento\ImportExport\Model\Export\Adapter\CsvFactory into your constructor
  2. Using the CsvFactory, you need to create an instance of the CSV Model: $csvModel = $this->csvFactory->create(['destination' => 'path/to/your/file.csv']);
  3. Using the CSV Model, write out your data: $csvModel->writeRow(['your' => 'data']);
  4. Inject an instance of \Magento\ImportExport\Model\ImportFactory into your constructor
  5. Using the ImportFactory, you need to instantiate the Import Model: $importModel = $this->importModelFactory->create();
  6. Set any data you need to pass to the import model: $importModel->setData(['your' => 'data']);
  7. Get an instance of the CSV source model: $sourceModel = ImportAdapter::findAdapterFor( 'path/to/your/file.csv', $this->filesystem->getDirectoryWrite(DirectoryList::ROOT), $importModel->getData('_import_field_separator') );
  8. Validate your import: $isValid = $importModel->validateSource($sourceModel);
  9. Handle the validation results: if ($importModel->getProcessedRowsCount() === 0 || !$isValid || $importModel->getErrorAggregator()->getErrorsCount()) { // Display or log the error return; }
  10. Run the import: $importModel->importSource();

There's a lot more involved in the error handling, but this should at least get you started.

Related Topic