I have created one form. In function buildForm() I'm firing query by getting parameters from url.

So suppose my url is [example.com/myform/myshort-title][1]

Now during form build, it gets the default argument as url parameter, and render results of query.Let's say my query result is an array of entity ids.

$entityids = array(1,2,3,4,5,6);

public function buildForm(array $form, FormStateInterface $form_state, $short_title = '') {

$query = \Drupal::entityQuery('mycustomentity');
$query->condition('colname', $short_title);
$entity_ids = $query->execute();


Now in form submit handler, I'm rebuilding form state like shown below:

class MyForm extends FormBase {

  protected $myvar;
  protected $step;
  protected $correct_ans;

  public function buildForm(array $form, FormStateInterface $form_state, $short_title = '') {

    $query = \Drupal::entityQuery('mycustomentity');
    $query->condition('colname', $short_title);
    $entity_ids = $query->execute();
    $i = 0;
    foreach ($node_storage as $nodeID=>$nodeData) { 
       if ($i == $this->step)  {
echo $this->correct_ans;

       $correctAns = CategoryController::getCorrectAnswer($op,$entityid);
       $form['answer'][$i] = array(
            '#type' => 'hidden',
            '#value' => $correctAns,

public function submitForm(array &$form, FormStateInterface $form_state) {
$aString = $form_state->getValue('answer');
foreach ($aString[0] as $key1 => $value1) {

                         $this->correct_ans= $value1;




Debugging results give:

At first, when form gets loaded, it takes default parameter as argument from url == short_title.

print_r($entity_ids); gives array(1,2,3,4,5) print_r($correctans); echo "<br>";gives arary(0=>myanswer1)

Hit Submit

array(1,2,3,4,5) array(0=>myanswer1)

array(1,2,3,4,5) array(0=>myanswer1) array(0=>myanswer2) array(0=>myanswer1) array(0=>myanswer3)

and echo $this->correct_ans; always gives myanswer1. On every form submit form gets rebuild and $this->correct_ans takes default array value which is array(0=>myanswer1)

But I want, On first submit, I get array(0=>myanswer1), On second submit I want array(0=>myanswer2), On third submit I want array(0=>myanswer3) and so on...

Where I'm doing mistake?Please help.


1 Answer 1


You are trying to store state values into a protected variable in the class. That will not work. You will have to store state values into the form.

So instead of using


and other class properties to store values use

$form_state->set('step', $value);

to persist values between submissions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.