drupaldrupal-8drupal-nodes

add some custom information to node drupal 8


I need to update my referential entity with new values ​​that are inserted every time a user visits the page. I tried to use this code but unfortunately, the latter does not add a value but replaces all of them. I am attaching the code that I used in the hope that someone can help me with this problem. thank you

nodeObj = Node::load(implode($nids));
    $nodeObj->set('my_field', $current_user_id);
    $nodeObj->save(); 

Solution

  • If I understand your issue correctly, your code is overwriting the entire value of my_field rather than appending a new value. Also, the implode() and the $nids variable suggest to me that you may be trying to perform this function on multiple nodes at once, which your current code will not do.

    1. Make sure my_field is an ItemList field of some kind.
    2. Try this code:
    $nodeObjs = Node::loadMultiple($nids);
    foreach ($nodeObjs as $nodeObj) {
       $nodeObj->my_field->appendItem($current_user_id);
       $nodeObj->save();
    }