We have an Article
content type which has an Entity Reference field called field_document
that is linked to the Media
bundle type of Document
. In mymodule
we need to write a hook that will take the current field_document.id
(which maps to Document.mid
) and return all the Article
pages where field_document.target_id = mid
.
Goal
- Take the current node id and retrieve the
Document
entity that is linked to by accessingfield_document
- Using the
field_document
value, return otherArticles
that have the same value forfield_document
- Perform the query in a
hook_preprocess_node()
hook.
Question
- How can we retrieve all the nodes based on the $mid?
When we tried
We were able to return all Articles
. However when we add ->condition('field_document.target_id, $mid)
, we get zero results even though we know there are Articles
where the field_document.target_id = $mid
.
function mymodule_preprocess_node($variables) {
$node = $variables['node'];
$linked_document_id = $node->get('field_document')->first()->getValue()['target_id'];
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$query = $node_storage->getQuery()
->condition('type', 'article')
->condition('status', 1);
$and = $query->andConditionGroup();
$and->condition('field_document', $linked_document_id, '=');
$query->condition($and);
$results = $query->execute();
// returns zero
ksm($results);
}
We also tried using $and->condition('field_document.target_id', $linked_document_id, '=');
, but that did not return any results either.
Additional steps we tried, but with similar issue.
function mymodule_preprocess_node($variables) {
$node = $variables['node'];
$linked_document_id = $node->get('field_document')->first()->getValue()['target_id'];
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$query = $node_storage->getQuery()
->condition('type', 'article')
->condition('status', 1);
->condition('field_document', $linked_document_id, '=');
$results = $query->execute();
// returns zero
ksm($results);
}
andConditionGroup()
to see if we got separate results, but that did not happen.$linked_document_id
contains the value you think it should?field_document
is required and will always have a value. I tried using a bunch of kint statements as well. for some reason the->condition('field_document', $linked_document_id, '=');
just returnszero
results;
in it shouldn't be after->condition('status', 1);
try with ` $node_storage = \Drupal::entityTypeManager()->getStorage('node'); $query = $node_storage->getQuery() ->condition('type', 'article') ->condition('status', 1) ->condition('field_document', $linked_document_id, '='); $results = $query->execute();`