How $form_state->setRebuild(); works? 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-&gt;condition('colname', $short_title);
$entity_ids = $query-&gt;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-&gt;condition('colname', $short_title);
    $entity_ids = $query-&gt;execute();
    $i = 0;
    foreach ($node_storage as $nodeID=&gt;$nodeData) { 
       if ($i == $this-&gt;step)  {
echo $this-&gt;correct_ans;

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

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

                         $this-&gt;correct_ans= $value1;

}     
   $form_state-&gt;setRebuild();
   $this-&gt;step++;

    }


}


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 "&lt;br&gt;";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-&gt;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.
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

$this-&gt;step


and other class properties to store values use

$form_state-&gt;set('step', $value);


to persist values between submissions.