1

I'm trying to access the comment field value in controller. With the following code I'm able to access the particular comment object.

$comment = \Drupal::entityManager()->getStorage('comment')->load($commentID);

When I try print_r for the $comment variable, I can see the fully loaded comment object. enter image description here

I understand I cannot access the values by traversing the object since the values are protected. I tried $comment->get('subject')->value function, this time its looping and doesn't return any results.

How do I achieve retrieving the value of specific fields associated with comment entity?

3

It is better to use kint() function of the devel module for debugging entities because you will get also a list of available public methods.

You cannot get all comment fields values by looping them as different fields have different array result structure.

Using $comment = \Drupal::entityTypeManager()->getStorage('comment')->load($commentID) you get full comment object.

$comment->get('comment_body)->value you get comment body value as it uses some text format (eg. full html).

You also can covert comment object to array $comment = $comment->toArray().

  • I wouldn't recommend working with the return value of toArray() but it is very useful to use with kint()/debug()/var_dump(). It doesn't contain computed properties like ->entity, though. – Berdir Nov 25 '16 at 19:54
  • Thank you @Andrew Nim and Berdir, the kint() function of devel module helps. PHP print_r should not be used for complex object with lot of iterations, I got it. – pown Nov 28 '16 at 7:06

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.