I want to load a certain node. I don't know the id of the node but I do know that it has a certain hash field that is unique and I know that hash.
I want to load the node via the hash field. How can I do that?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityYou can achieve by using EntityFieldQuery.
For D8 EntityFieldQuery has been rewritten.
Drupal 8:
$query = \Drupal::entityQuery('entity_test');
$default_langcode_group = $query->andConditionGroup()
->condition('user_id', $properties[$default_langcode]['user_id'], '=', $default_langcode)
->condition('name', $properties[$default_langcode]['name'], '=', $default_langcode);
$langcode_group = $query->andConditionGroup()
->condition('name', $properties[$langcode]['name'], '=', $langcode)
->condition("$this->field_name.value", $field_value, '=', $langcode);
$result = $query
->condition('langcode', $default_langcode)
->condition($default_langcode_group)
->condition($langcode_group)
->sort('name', 'ASC', $default_langcode)
->execute();
How do I fetch the values of an entity's field?
$query = \Drupal::entityQuery('node')
->condition('status', 1)
->condition('changed', REQUEST_TIME, '<')
->condition('title', 'cat', 'CONTAINS')
->condition('field_tags.entity.name', 'cats');
$nids = $query->execute();
Node::
to load said nodes, correct?
The quickest way to load a specific node by field value is to use the method loadByProperties()
.
You specify one or more field values and returned is an array containing the nodes matching the field values:
$nodes = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties([
'title' => $title,
'field_hash' => 'YOUR_HASH',
]);
Normally you loop over the nodes. In your case you are looking for one specific node. A single node is also returned in array, so apply reset()
and this returns either the node or NULL if nothing was found:
if ($node = reset($nodes)) {
// found $node that matches the title
}
$node = reset...
) since the hash itself is unique.
To load entities (nodes, users etc.) based on an array of multiple possible values/types you can use the entity query or entity type manager like that:
// Get all node IDs of multiple node types.
$query = \Drupal::entityQuery('node')
->condition('type', ['page', 'news'], 'IN');
$nids = $query->execute();
// Get all nodes of multiple node types.
$nodes = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties([
'type' => ['page', 'news'],
]);