Drupal - How to set value for multivalue field in drupal 8 programmatically

I would rewrite your code like this.
N.B.: This an edited version of the original answer, following some helpful points coming from the comments.

$poll = Poll::load($pollid);

$poll->question->setValue(['value' => 'test']);

$target_ids = array(13,14,15);
foreach($target_ids as $target_id){
  $poll->choice->appendItem($target_id);
}
$poll->save();

Hope this does it!


You can work with multi value fields like an array. The field interface will translate this to store it in the database. To simplify it even more:

$target_ids = array(13,14,15);
$node_poll = Poll::load($pollid);
foreach($target_ids as $target_id) {
  $node_poll->choice[] = $target_id;
}
$node_poll->question->value = 'test';
$node_poll->save();

This will add the id's to the field, not overwrite the existing ones. If you want to do this, you can set an empty array at the beginning.

Tags:

8

Polls