In an implementation of hook_node_insert()
, I have the following three lines of code:
dpm($entity, 'entity');
$title = $entity->getTitle();
dpm($title, 'title');
From the first dpm()
I get:
entity =>
Drupal\node\Entity\Node {#1632 ▼
+in_preview: null
#values: array:27 [▼
...
"title" => array:1 [▼
"x-default" => array:1 [▼
0 => array:1 [▼
"value" => "Expected title"
]
]
...
I.e. the title field output by the variable dumper is the title field I expected to see.
The second dpm()
produces:
title =>
"The previous title"
I.e. when I extract the title from the entity, using the getTitle()
method, I get a different value. The value is from an entity (node) the I load in a operations link controller (overriding ControllerBase
), but it not saved inside the controller, and should not fire hook_node_insert()
.
I construct and save a new node in the controller, using this code:
$node = \Drupal::entityTypeManager()->getStorage('node')->create([
'type' => 'my_type',
'body' => 'Body',
]);
$node->setTitle('Expected title');
$node->save();
I assume that this is the $node->save();
that fires hook_node_insert
.
What is going on here?
Why does the bogus title appear in the hook, and how do I get the expected result?
For the record: I am not changing the node in hook_node_insert
. I am deleting it if the title meets certain criteria. I am unable to use a constraint for preventing it from being created for reasons unrelated to this question.