7

I was saving poll choices Programmatically in Drupal 8. I have used Drupal8 Poll choices module.

$node_poll = Poll::load($pollid);
//print_r($node_poll);exit;
$i = array(13,14,15);
foreach($i as $key => $value){
  $node_poll->choice->setValue(
        [
            ['target_id' => $value]
        ]
  );
// But I want to save multiple target ids. now this is saving 15 all the time.

}
$node_poll->question->setValue([
  'value' => 'test',
]);
$node_poll->save();

The following snippet is working fine.

$node_poll->choice->setValue(
        [
            ['target_id' => 13]
       ],
       [
            ['target_id' => 14]
       ],
        [
            ['target_id' => 15]
       ]
    );

How can I, make target ids to be saved dynamically?

  • 1
    I cleaned up your question some, could you check it and make sure I got everything right? – Stefanos Petrakis Apr 24 '16 at 11:34
  • yes, but I need an answer for it could you please help? In Drupal 7 Array was working fine.I mean if a pass values in array they will work but in drupal 8 passing values in array does not work. – harsh_behl_0007 Apr 24 '16 at 11:35
  • Hello @harsh, I just saw that you chose another answer as correct. Could you provide some feedback about the reason? Some comment? Would be very useful. – Stefanos Petrakis Apr 25 '16 at 13:22
13

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!

  • 1
    Thanks for the help. I am newbie in drupal8 thanks very much you saved my hours. – harsh_behl_0007 Apr 24 '16 at 11:42
  • 1
    You are welcome. Did you try it then and it works? If so, you should also accept the answer. If not, let me know, and we can look at this further. – Stefanos Petrakis Apr 24 '16 at 11:43
  • Two notes: $node_poll as a variable makes no sense, polls in D8 are not nodes. Second, you can also just directly call $poll->choice->appendItem(13); etc. in a loop, a lot simpler. – Berdir Apr 24 '16 at 14:24
3

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.

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.