0

I'm attempting to render certain fields within a block plugin but I'm not sure where to start as far as accessing the fields so I can render them.

I'm able to get the node ids after I perform the query using the following code.

    $query = \Drupal::entityQuery('node')
        ->condition('type', 'blog_post');
    $nids = $query->execute();

This retrieves the ids that I need based on the query but I don't know how to access custom fields like blog_summary.

I looked into some functions like getFieldDefinitions(). But I'm not sure how to make use of it. I attempted some things using getStorage but I assumed I wouldn't want to go that route since I'm not attempting to make any changes to the nodes I only want to access their fields.

2

Try this:

public function build() {
  $query = \Drupal::entityQuery('node')
    ->condition('type', 'blog_post');
  $nids = $query->execute();

  $build = [];
  foreach ($nids as $nid) {
    $node = Node::load($nid);
    $build[] = $node->blog_summary->view();
  }
  return $build;
}
| improve this answer | |
  • 1
    If you have to load the nodes anyway you can do that immediately via: ' $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'blog_post']);' – Maouna Jun 23 '16 at 14:19
  • I'm receiving an error Fatal error: Class 'Drupal\my_plugin\Plugin\Block\Node not found. I thought it might have to do with the namespace but adding use Drupal\Core\Node at the top didn't work, and I already have use Drupal\Core\Entity – Matt Jun 23 '16 at 15:01
  • 1
    You have to add use Drupal\node\Entity\Node; The node entity is provided by the node module of core. – Maouna Jun 23 '16 at 15:09
1

It depends on what type of fields you want to render. For strings and ints you may just use

$node = Node::load($nid);
$build[] = $node->field_name->value;
| improve this answer | |
  • How would I retrieve an image? – Matt Jun 23 '16 at 16:04
  • 1
    Use the target_id of your entity_reference like this: $node->get('image_field')->target_id. Then load the Image entity with that target_id. – Rainer Feike Jun 24 '16 at 7:32
  • By target_id do you mean the node id? – Matt Jun 24 '16 at 14:11
  • 1
    No, the target_id is the entity_id of the image entity that the entity reference field in $node points to. – Rainer Feike Jun 26 '16 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.