hook_entity_presave()
and hook_ENTITY_TYPE_presave()
should not assume the entity has been edited using a form, or a page has been shown to the users. Those hooks are also invoked when an entity is programmatically created, for example with the following code, which could also be used in a hook_cron()
implementation.
$values = [
'type' => 'article',
'title' => 'The article title',
'uid' => 1,
'status' => TRUE,
];
$node = \Drupal::entityManager()->getStorage('node')->create($values);
$node->save();
The hook invoked before an entity is rendered is hook_entity_view()
(or hook_ENTITY_TYPE_view()
).
Using one of those hooks, a module can add an extra rendering array in $build
, for example with $build['#attached']['library'][] = 'js/url-parameter.js';
.
As the example code, $display->getComponent()
should be used to verify the entity field has been set to be rendered, since administrator users can hide fields from /admin/structure/types/manage/article/display (for the Article content type). For example, with the following settings, I would hide a custom entity field and the Tags field for the Article content type.
I would also check the value of $view_mode
passed to those hooks as that value says why the node is rendered. For example, when the Search module indexes the nodes, $view_mode
is equal to 'search_index'
; when a node is added to a RSS feed, $view_mode
is equal to 'rss'
. In those cases, you probably don't want to add a library.