Score:2

How can I load the last nine created nodes?

cn flag

I want to get the latest nine nodes in a preprocess hook. I am using the following code, but it returns all the news nodes.

$entities = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'news']);

Is it possible to load only the last nine created nodes using loadByProperties()?

Score:6
us flag

loadByProperties() just loads entities given the value of some of their properties. It doesn't sort the entities basing on some criteria nor does it return the last X entities. For that, you need to use the instance returned by \Drupal::entityQuery().

$query = \Drupal::entityQuery('node');
$query->accessCheck(FALSE)
  ->condition('entity_type', 'news')
  ->sort('changed', 'DESC')
  ->range(0, 9);

$nids = $query->execute();

$nids will contain an array of node IDs you can use to load the nodes, for example with \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids).

I used accessCheck(FALSE) to avoid Drupal would return only the nodes to which the currently logged-in user has access. To let Drupal return only the nodes to which the currently logged-in user has access, that line must be removed.

Zuhair avatar
mv flag
Isn't the entity type given as ```->condition('type', 'news')``` ?
mauzilla avatar
cn flag
excellent answer, thank you for your help
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.