I’m trying to write a drush command to resave all the nodes on my site.
I searched for a module and found the Resave All Nodes module, but its drush command isn’t ready yet. So I decided to try to write it myself.
However, I can’t get my nodes to re-save with $entity->save()
, and I don’t understand why.
<?php namespace Drupalresave_all_nodesCommands; use DrupalCoreEntityEntityTypeManagerInterface; use DrupalnodeEntityNode; use DrushCommandsDrushCommands; /** * A Drush command class for Resave All Nodes module conversions. */ class ResaveAllNodesCommands extends DrushCommands { /** * The entity type manager. * * @var DrupalCoreEntityEntityTypeManagerInterface */ private $entityTypeManager; /** * Constructs a ResaveAllNodesCommands object. * * @param DrupalCoreEntityEntityTypeManagerInterface $entity_type_manager * The entity type manager. */ public function __construct(EntityTypeManagerInterface $entity_type_manager) { $this->entityTypeManager = $entity_type_manager; parent::__construct(); } /** * Resave all nodes. * * @command resave-all-nodes:resave * * @usage drush resave-all-nodes:resave * Resave all nodes on the site. * * @aliases ran */ public function resaveAllNodes() { $my_node = Node::load(1); $my_node->save(); Drupal::logger('resave_all_nodes')->notice("node 1 saved!"); } }
When I run the command, the logs show the logger notices:
- I see "node 1 saved!" in the logs
- I have another log message in
hook_entity_presave()
, which also appears
But, when I go to /admin/content
, the "date updated" for node 1 has not changed. Also, the content of the node is not resaved.
If I go to node/1/edit
and re-save manually, the node is re-saved as I would expect (the updated date is updated, and the field values are updated).
So, why does node->save()
silently fail (the update date and field values remain the same), when saving manually works?
I have a few custom modules and I disabled them and rebuilt the cache, but the problem remains.