1

I'm currently working on a simple reviewing system. I've created a custom comments type ("Review") with an integer list ("Rating") that can be added to my nodes. Now, while displaying the note, I would like to get an average rating based on the reviews posted.

I am quite new to Drupal, and I thought that I might achieve this by creating a custom twig template for the product-type nodes and getting the required value in a preprocess function.

I succeeded in getting the field_reviews object with

$variables['comment_field'] = $node->get('field_reviews');  

and when I kint()ed it out, I got a really big file structure, but the required data was in there.

However, whenever I tried following the path down there through dozens of variables and arrays, when I reached the review itself, kinting yielded NULL or the page didn't load at all.

I'm getting the feeling that this approach is not ideal and that I must've overlooked something much easier, but I can't seem to figure out what.

3

The comment field doesn't contain the comments, it just contains settings and statistics (e.g. open or closed).

To get the comments, you need to do an entity query and get all comments that have point to your node of your type, load them and then calculate the average from them.

Also, see http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet on how to work with content entities and fields. kint() is highly misleading and confusing.

Update. Instead of having to load all comments and calculate the average yourself, you should be able to do an aggregate entity query and get the average value of your field directly: https://www.drupal.org/node/1918702

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.