Im building a custom filter in Drupal 8 based on some queries.

I got this already, here im filtering by values on body:

$query = db_select('node__body', 'n')
                            ->condition('n.body_value', "%" . $searchWord . "%", 'LIKE')
                            ->condition('n.bundle', 'mycontenttype');
     $getList = $query->execute()->fetchAll();

Then i pass the variable to the Twig:

return [
            '#filters' => $getList,

In the twig im doing:

{% for oneItem in filters %}

But im unable to get the title of the node here, what im missing?

1 Answer 1

  1. You shouldn't do queries like like that. You should use EntityQuery. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Query%21QueryInterface.php/function/QueryInterface%3A%3Acondition/8.8.x and EntityFieldQuery to search Content Type for text and select matching Nodes EntityQuery will return the nids. Then use the node storage's loadMultiple to get the node themselves. Typically something like Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids)
  2. I would expect the Node title would be gotten in your loop with {{ oneItem.title }}. If that's not working I suggest installing and enabling the devel module, and sticking {{ dump(filters) }} in your custom template to investigate the structure you're getting
  • EntityQuery is available in Drupal 8?, im not using D7, sorry. Feb 26, 2020 at 2:20
  • 1
    Now im using this but im just getting the nids and not the content: $query = \Drupal::entityQuery('node') ->condition('type', 'contentType') ->condition('body', "%" . $getSearch . "%", 'LIKE'); Feb 26, 2020 at 2:31
  • EntityQuery is in Drupal 8, which you said you're using in the OP.
    – beltouche
    Feb 26, 2020 at 2:51
  • Im using Drupal 8 as you can see on my question, im only getting array of ids in my template and i need the node info, photos, title, body, this is what im getting: array(2) { [114]=> string(2) "50" [115]=> string(2) "51" } Feb 26, 2020 at 2:52
  • 2
    Ok i got it working, thank you so much, the final result is: $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($getList); $getNodes = []; foreach ($nodes as $entity){ $getNodes[] = ['id' => $entity->id(), 'label' => $entity->label()]; } Feb 26, 2020 at 3:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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