1

I use this function to synchronize a comment field with the value from a field that exists in the node the comment belongs to.

function mymodule_comment_create(\Drupal\comment\CommentInterface $comment) {
  $node = $comment->getCommentedEntity();
  if ($node && $node instanceof \Drupal\node\NodeInterface) {
    if ($node->hasField('field_example')) {
      $comment->subject->value = $node->field_example->value;
    }
  }
}

How could I achieve the opposite? When a comment is submitted with the field field_rating, the field_average_rating field of the node should be updated.

How could I achieve that?

1
  • kiamlaluno my question is for drupal 8 only. There is already a solution and a sandbox module for what I am asking for drupal 7 drupal.stackexchange.com/questions/15436/… but that does not work in drupal 8. Could you please add back the number of the version in the title so there is no confusion? Thank you!
    – Ioannis
    Commented Jan 26, 2018 at 17:17

1 Answer 1

0

You could implement the same hook hook_comment_create() but just inverse the assignment you do on the comment as in your code, for example:

function mymodule_comment_create(\Drupal\comment\CommentInterface $comment) {
  $node = $comment->getCommentedEntity();
  if ($node && $node instanceof \Drupal\node\NodeInterface) {
    if ($node->hasField('node_field') && $comment->hasField('comment_field') && !empty($comment->comment_field->value)) {
      $node->node_field->value = $comment->comment_field->value;
    }
  }
}
1
  • Thank you adrum99 but I just tried that and nothing happened. The Value of the node field did not change... Here is my code function hello_comment_create(\Drupal\comment\CommentInterface $comment) { $node = $comment->getCommentedEntity(); if ($node && $node instanceof \Drupal\node\NodeInterface) { if ($node->hasField('field_nod') && $comment->hasField('field_com') && !empty($comment->field_com->value)) { $node->field_nod->value = $comment->field_com->value; } } }
    – Ioannis
    Commented Jan 26, 2018 at 16:44

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.