{"id":55761,"date":"2022-11-28T10:24:50","date_gmt":"2022-11-28T04:54:50","guid":{"rendered":"https:\/\/www.tothenew.com\/blog\/?p=55761"},"modified":"2022-11-28T10:26:18","modified_gmt":"2022-11-28T04:56:18","slug":"use-drush-command-with-batch-to-update-node","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/use-drush-command-with-batch-to-update-node\/","title":{"rendered":"Use Drush command with Batch to update Node"},"content":{"rendered":"<p>In this tutorial, we are going learn how to create\/update nodes with the help of the Drush command using\u00a0 Batch API in Drupal. For that, we need to create a custom module. The file structure will be like below:<\/p>\n<p>Example: In the below example, we are updating the article content type <strong>Title<\/strong> field with a dummy value by dividing it into chunks of 100, similarly can add your own logic.<\/p>\n<p>To create a custom module, follow the below steps, which will help create a custom Drush Command <strong>update:node article.<\/strong><\/p>\n<ol>\n<li><strong>Create <em>BatchDrushCommand.php<\/em> file under the custom module\/Commands folder.<\/strong>\n<div>\n<pre>&lt;?php\r\n\r\nnamespace Drupal\\module_name\\Commands;\r\n\r\nuse Drupal\\Core\\Entity\\EntityTypeManagerInterface;\r\n\r\nuse Drupal\\Core\\Logger\\LoggerChannelFactoryInterface;\r\n\r\nuse Drush\\Commands\\DrushCommands;\r\n\r\n\/**\r\n\r\n* A Drush commandfile for defining the command and callback method to it.\r\n\r\n*\/\r\n\r\nclass BatchDrushCommand extends DrushCommands {\r\n\r\n\/**\r\n\r\n* Entity type service.\r\n\r\n*\r\n\r\n* @var \\Drupal\\Core\\Entity\\EntityTypeManagerInterface\r\n\r\n*\/\r\n\r\nprivate $entityTypeManager;\r\n\r\n\/**\r\n\r\n* Logger service.\r\n\r\n*\r\n\r\n* @var \\Drupal\\Core\\Logger\\LoggerChannelFactoryInterface\r\n\r\n*\/\r\n\r\nprivate $loggerChannelFactory;\r\n\r\n\/**\r\n\r\n*\r\n\r\n* @param \\Drupal\\Core\\Entity\\EntityTypeManagerInterface $entityTypeManager\r\n\r\n* Entity type service.\r\n\r\n* @param \\Drupal\\Core\\Logger\\LoggerChannelFactoryInterface $loggerChannelFactory\r\n\r\n* Logger service.\r\n\r\n*\/\r\n\r\npublic function__construct(EntityTypeManagerInterface$entityTypeManager, LoggerChannelFactoryInterface$loggerChannelFactory) {\r\n\r\n$this-&gt;entityTypeManager = $entityTypeManager;\r\n\r\n$this-&gt;loggerChannelFactory = $loggerChannelFactory;\r\n\r\n}\r\n\r\n\/**\r\n\r\n* Update Node.\r\n\r\n*\r\n\r\n* @param string $type\r\n\r\n* Type of node to update\r\n\r\n* Argument provided to the drush command.\r\n\r\n*\r\n\r\n* @command update:node\r\n\r\n* @aliases update-node\r\n\r\n*\r\n\r\n* @usage update:node article\r\n\r\n*\/\r\n\r\npublic functionupdateNode($type = '') {\r\n\r\n\/\/ 1. Log the start of the script.\r\n\r\n$this-&gt;loggerChannelFactory-&gt;get('module_name')-&gt;info('node update started');\r\n\r\n\/\/ Check the type of node given as argument, if not, set article as default.\r\n\r\nif (strlen($type) == 0) {\r\n\r\n$type = 'article';\r\n\r\n}\r\n\r\n\/\/ 2. Retrieve all nodes of this type.\r\n\r\ntry {\r\n\r\n$storage = $this-&gt;entityTypeManager-&gt;getStorage('node');\r\n\r\n$query = $storage-&gt;getQuery()\r\n\r\n-&gt;condition('type', $type)\r\n\r\n-&gt;condition('status', '1');\r\n\r\n$nidsCount = $query-&gt;execute();\r\n\r\n$nidsCount = count($nidsCount);\r\n\r\n}\r\n\r\ncatch (\\Exception$e) {\r\n\r\n$this-&gt;output()-&gt;writeln($e);\r\n\r\n$this-&gt;loggerChannelFactory-&gt;get('module_name')-&gt;warning('Error found @e', ['@e' =&gt; $e]);\r\n\r\n}\r\n\r\n\/\/ 3. Create the operations array for the batch.\r\n\r\n$operations = [];\r\n\r\n$numOperations = 0;\r\n\r\n$batchId = 1;\r\n\r\nif ($nidsCount &gt; 0) {\r\n\r\nfor ($i = 0; $i &lt; $nidsCount;) {\r\n\r\n$query = $storage-&gt;getQuery()\r\n\r\n-&gt;condition('type', $type)\r\n\r\n-&gt;range($i, 100)\r\n\r\n-&gt;condition('status', '1');\r\n\r\n$nids = $query-&gt;execute();\r\n\r\n$articleId = array_keys($nids);\r\n\r\n$operations[] = [\r\n\r\n'\\Drupal\\module_name\\UpdateNode::articleUpdate',\r\n\r\n[\r\n\r\n$batchId, $articleId,\r\n\r\n],\r\n\r\n];\r\n\r\n$batchId++;\r\n\r\n$numOperations++;\r\n\r\n$i = $i + 100;\r\n\r\n}\r\n\r\n}\r\n\r\nelse {\r\n\r\n$this-&gt;logger()-&gt;warning('No nodes of this type @type', ['@type' =&gt; $type]);\r\n\r\n}\r\n\r\n\/\/ 4. Create the batch.\r\n\r\n$batch = [\r\n\r\n'title' =&gt; t('Updating @num node(s)', ['@num' =&gt; $numOperations]),\r\n\r\n'operations' =&gt; $operations,\r\n\r\n'finished' =&gt; '\\Drupal\\module_name\\UpdateNode::articleUpdateFinished',\r\n\r\n];\r\n\r\n\/\/ 5. Add batch operations as new batch sets.\r\n\r\nbatch_set($batch);\r\n\r\n\/\/ 6. Process the batch sets.\r\n\r\ndrush_backend_batch_process();\r\n\r\n}\r\n\r\n}<\/pre>\n<\/div>\n<pre><\/pre>\n<\/li>\n<li><strong>\u00a0Create a Helper File named <em>UpdateNode.php<\/em> in which we will write the articleUpdate and articleUpdateFinished function\u00a0<\/strong>\n<div>\n<pre>&lt;?php\r\n\r\nnamespace Drupal\\module_name;\r\n\r\n\/**\r\n\r\n* Class RevisionBatchProcess.\r\n\r\n*\/\r\n\r\nclass UpdateNode {\r\n\r\n\/**\r\n\r\n* articleUpdate callback.\r\n\r\n*\/\r\n\r\npublic function articleUpdate($id, $articleId, &amp;$context) {\r\n\r\nforeach ($articleId as $nid) {\r\n\r\n\/\/ Simulate long process by waiting 100 microseconds.\r\n\r\nusleep(100);\r\n\r\n$entityService = \\Drupal::entityTypeManager();\r\n\r\n$articleObject = $entityService-&gt;getStorage('node')-&gt;loadRevision($nid);\r\n\r\n$articleObject-&gt;set('title', 'update-title');\r\n\r\n$articleObject-&gt;save();\r\n\r\n$context['results'][] = $id;\r\n\r\n$context['message'] = t('processing \"@id\" @response',\r\n\r\n['@id' =&gt; $id, '@response' =&gt; $nid]\r\n\r\n);\r\n\r\n}\r\n\r\n}\r\n\r\n\/**\r\n\r\n* articleUpdateFinished callback.\r\n\r\n*\/\r\n\r\npublic function articleUpdateFinished($success, array $results, array $operations) {\r\n\r\n$messenger = \\Drupal::messenger();\r\n\r\nif ($success) {\r\n\r\n$messenger-&gt;addMessage(t('@count results processed.', ['@count' =&gt; count($results)]));\r\n\r\n}\r\n\r\n}\r\n\r\n}<\/pre>\n<\/div>\n<p>Once the code is added to the module, enable the module or if you are using the existing module, then clear the drupal cache and run the <strong>drush update:node article<br \/>\n<\/strong>command.<\/p>\n<p>Please add comments if you have any queries or doubts.<\/li>\n<\/ol>\n<div class=\"ap-custom-wrapper\"><\/div><!--ap-custom-wrapper-->","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we are going learn how to create\/update nodes with the help of the Drush command using\u00a0 Batch API in Drupal. For that, we need to create a custom module. The file structure will be like below: Example: In the below example, we are updating the article content type Title field with a [&hellip;]<\/p>\n","protected":false},"author":1513,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":115},"categories":[3602],"tags":[5043],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/55761"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/1513"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=55761"}],"version-history":[{"count":3,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/55761\/revisions"}],"predecessor-version":[{"id":55853,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/55761\/revisions\/55853"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=55761"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=55761"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=55761"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}