closedquestion-8.x-3.x-dev/src/Form/QuestionForm.php
src/Form/QuestionForm.php
<?php
namespace Drupal\closedquestion\Form;
use Drupal\closedquestion\Entity\ClosedQuestionInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Class QuestionForm.
*
* @package Drupal\closedquestion\Form
*/
class QuestionForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'closedquestion_question_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, ClosedQuestionInterface $closedQuestion = NULL) {
$form_state->getStorage()['closedquestion'] = $closedQuestion;
// Disable form cache because stored entity cannot be serialized.
$form_state->disableCache();
$form['#cache'] = ['max-age' => 0];
if (isset($closedQuestion->question) && $closedQuestion->question) {
$form = $closedQuestion->question->getForm($form_state);
if (!isset($closedQuestion->noReset)) {
$form['reset'] = array(
'#type' => 'submit',
'#value' => 'Reset',
);
}
$form['#attached']['library'][] = 'closedquestion/closedquestion.core';
}
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
/** @var \Drupal\closedquestion\Entity\ClosedQuestionInterface $closedquestion */
$closedquestion = $form_state->getStorage()['closedquestion'];
/** @var \Drupal\closedquestion\Question\CqQuestionInterface $question */
$question = $closedquestion->question;
if ($form_state->getTriggeringElement()['#value'] == $form_state->getValue('reset') && !isset($closedquestion->noReset)) {
$question->reset();
\Drupal::messenger()->addMessage(t('Answer Reset.'));
$url = URL::fromRoute('<current>');
$form_state->setRedirectUrl($url);
\Drupal::moduleHandler()->invokeAll('closedquestion_reset', [$question]);
}
else {
$question->submitAnswer($form, $form_state);
$form_state->setRebuild();
}
}
}
