2

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?

2

1 Answer 1

4

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().

2
  • 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
    Commented Nov 25, 2016 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
    Commented Nov 28, 2016 at 7:06

Your Answer

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

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