Programmatically create a poll and add choice in Drupal 9.
September 10, 2022
In Drupal 9 poll and poll choice both are separate entity.
Create a Poll Entity :
/* Poll will be created here. */
$poll = Poll::create(array(
'id' => 'poll',
'uid' => '50',
'question' => $title,
'anonymous_vote_allow' => '1',
'cancel_vote_allow' => '0',
'result_vote_allow' => '1',
'status' => '0',
));
Create a Poll Choice Entity :
/* Choices will be added here. */
$choices = PollChoice::create(array(
'id' => 'poll_choice',
'uid' => '50',
'choice' => $data
));
$choices->save();
$choice_id = $choices->id();
Adding created choice to the poll :
$poll->choice->appendItem($choice_id);
$poll->save();