public function ApprovalPollViewForm::save in Advanced Poll 8
Save a user's vote submit function.
Parameters
array $form:
\Drupal\Core\Form\FormStateInterface $form_state:
Overrides PollViewForm::save
File
- src/
Form/ ApprovalPollViewForm.php, line 245
Class
- ApprovalPollViewForm
- Class ApprovalPollViewForm
Namespace
Drupal\advpoll\FormCode
public function save(array $form, FormStateInterface $form_state) {
$choices = $form_state
->getValue('choice');
// Make array from single vote to use the same code.
if (!is_array($choices)) {
$choices = [
$choices => $choices,
];
}
$storagePollChoice = \Drupal::entityTypeManager()
->getStorage('poll_choice');
foreach ($choices as $index => $choice) {
if ($choice) {
if ($index == self::writeInIndex) {
// Add write-in options if exists.
$writeInOptions = $this
->getWriteInOptions($form_state);
$pollOptions = $this->poll
->getOptions();
foreach ($writeInOptions as $writeInOption) {
// Check duplicate.
$chId = array_search($writeInOption, $pollOptions);
if (empty($chId)) {
// Create a new write-in option.
$pollChoice = $storagePollChoice
->create([
'choice' => $writeInOption,
]);
$pollChoice
->set('field_writein', TRUE);
$pollChoice
->save();
$this->poll
->get('choice')
->appendItem($pollChoice);
$this->poll
->save();
$chId = $pollChoice
->id();
}
$this
->saveVote($chId);
}
}
else {
// Add other options.
$chId = $index;
$this
->saveVote($chId);
}
}
}
\Drupal::messenger()
->addMessage($this
->t('Your vote has been recorded.'));
if ($this
->currentUser()
->isAnonymous()) {
// The vote is recorded so the user gets the result view instead of the
// voting form when viewing the poll. Saving a value in $_SESSION has the
// convenient side effect of preventing the user from hitting the page
// cache. When anonymous voting is allowed, the page cache should only
// contain the voting form, not the results.
$_SESSION['poll_vote'][$form_state
->getValue('poll')
->id()] = $form_state
->getValue('choice');
}
// In case of an ajax submission, trigger a form rebuild so that we can
// return an updated form through the ajax callback.
if ($this
->getRequest()->query
->get('ajax_form')) {
$form_state
->setRebuild(TRUE);
}
// No explicit redirect, so that we stay on the current page, which might
// be the poll form or another page that is displaying this poll, for
// example as a block.
}