Do you want to know how to Drupal?

Let's Drupal

migrate

How to run migration programmatically as a batch operations in Drupal 9?

It is quite easy to do instead of MigrateExecutable class, we need to use MigrateBatchExecutable and instead of import we need to use batchImport

use Drupal\migrate_tools\MigrateExecutable;


$migration = \Drupal::service('plugin.manager.migration')->createInstance($migration_id);
if (!empty($migration)) {
        // here we can set additional options like limit, update or force the import.
        $options = [
          'limit' => 0,
          'update' => 1,
          'force' => 1,
        ];

        $executable = new MigrateBatchExecutable($migration, new MigrateMessage(), $options);
        $executable->batchImport();
}

 


How to run a migration programmatically in Drupal 9?

The code bellow display how to execute the migration not through the command line, but through the code

First we need to load Migration. You can create it from a plugin, in this case the migration file is stored in migrations folder

 

use Drupal\migrate\MigrateMessage;
use Drupal\migrate_plus\Entity\Migration;
use Drupal\migrate_tools\MigrateExecutable;


// Load migration plugin.
$migration = \Drupal::service('plugin.manager.migration')->createInstance($migration_id);

or load it it from config entity

// Load migration from config entity.

$migration = \Drupal\migrate_plus\Entity\Migration::load($migration_id);

And then run the import

$executable = new MigrateExecutable($migration, new MigrateMessage());
$executable->import().

How to update URL for migration programmatically in Drupal 8?

Sometimes we need to dynamically set URL for migrations, for example we have specific parameters restricting results.

We have default configuration

source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: json
  urls:
    - 'http://your_domain/data.php'

 

// Get configuration factory.
$config_factory = \Drupal::configFactory();
// Load your migration configuration.
// Replace with your migration ID.
$migration_config = $config_factory->getEditable('migrate_plus.migration.[MIGRATION_ID]');
// Set your URL here.
$migration_config ->set('source.urls', ['YOUR_URL']);
$migration_config ->save();