What is the difference between using getValue()
and referencedEntities()
in order to get the paragraph on a node?
See example below. Both examples are used in a node template such as node--page--full.html.twig
and mymodule_preprocess_node()
hook.
Using getValue()
$paragraph = $node->field_paragraph->getValue();
foreach ( $paragraph as $pr ) {
// Get the entity using Paragraph::load(entity_id).
$pr_item = \Drupal\paragraphs\Entity\Paragraph::load($pr['target_id']);
// Now use $pr_item to get any field.
$pr_item_img = $pr_item->field_image;
}
Using referencedEntities()
$pr_field = $node->field_paragraph->referencedEntities();
foreach($pr_field as $pr) {
$item_image = $pr->get('field_image');
}
I am mainly concerned with the following:
- What is more performant?
- What is the best practice since both work?
- Is either method considered a magic method? I ask because you can use
$node->field_paragraph
as opposed to$node->get('field_paragraph')
foreach ($node->get('field_paragraph') as $item)
(without get works too but I prefer using get(), and then it's just $item->entity to get the paragraph, and then you can access its fields.