Drupal 10: Programmatically Running A Migration

If you want to run a migration programmatically you can do so using the MigrateExecutable object. To run it you just need to feed it a migration source plugin, which you can load separately.

use Drupal\migrate\MigrateExecutable;
use Drupal\migrate\MigrateMessage;

// Get the migration plugin manager service.
$pluginManagerMigration = \Drupal::service('plugin.manager.migration');

// Create the migration of your choice.
$articleMigration = $pluginManagerMigration->createInstance('article_migration');
$articleMigrationExecutable = new MigrateExecutable($articleMigration, new MigrateMessage());

// Run the migration.
$result = $articleMigrationExecutable->import();

The migration source plugin is essentially the content of your migration source yml file, converted into an object.

If you are using the Migrate Tools plugin you can also add options to the migrate executable. For instance, to restrict by and ID list do the following (note the different MigrateExecutable object).

use Drupal\migrate_tools\MigrateExecutable;
use Drupal\migrate\MigrateMessage;

// Get the migration plugin manager service.
$pluginManagerMigration = \Drupal::service('plugin.manager.migration');

// Define the source article ID we want to migrate.
$articleId = 1;

// Create the migration of your choice.
$articleMigration = $pluginManagerMigration->createInstance('article_migration');
$articleMigrationExecutable = new MigrateExecutable($articleMigration, new MigrateMessage(), ['idlist' => $articleId]);

// Run the migration.
$result = $articleMigrationExecutable->import();

This executable will run through the migration in the usual way. The return value from the import() method is in integer, detailing how the migration went. Use this to adapt your code to a migration pass or failure.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
8 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.