How to store value of variable if it is changed inside of ajax callback function? I have a form with several ajax callback functions.
And I have a variable which should change its value inside these  callback functions.
Unfortunately, I have faced with a problem. Namely, I don't know how to store the value of the variable after change. Because after the callback function executed the value is lost.

There is a little example of code.

class MyForm extends FormBase {
    public $i = 0;

public function buildForm(array $form, FormStateInterface $form_state){
    ...
    $form['add_more'] = [
        '#type' =&gt; 'submit',
        '#value' =&gt; 'Add More ...',
        '#ajax' =&gt; [
            'callback' =&gt; '::addMore',
        ]
    ];
    ...
}

public function addMore(array &amp;$form, FormStateInterface $form_state){
    ...
    $this-&gt;i++;
    ...
}
}


Here the variable $i doesn't increase its value whenever the button is being pressed.
Could you clarify, what should I do if I want the variable to increase its value whenever the button has been pressed ?
The ajax callback is not for form logic. It's only supposed to send back a new version of $form or part of it in a wrapper. Or in more advanced cases a collection of ajax commands.

Use instead buildForm(). You can check which button was clicked with $form_state-&gt;getTriggeringElement().      

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

    $form['#prefix'] = '&lt;div id="ajax_wrapper"&gt;';
    $form['#suffix'] = '&lt;/div&gt;';

    $i = $form_state-&gt;get('elem') ? $form_state-&gt;get('elem') : 1;
    $trigger = $form_state-&gt;getTriggeringElement();
    if (isset($trigger['#ajax']['callback']) &amp;&amp; $trigger['#ajax']['callback'] === '::addMore') {
      $i++;
    }
    $form_state-&gt;set('elem', $i);

    $form['counter'] = [
      '#markup' =&gt; $form_state-&gt;get('elem') ?? 1,
    ];

    $form['btn'] = [
      '#type' =&gt; 'button',
      '#value' =&gt; 'Btn',
      '#ajax' =&gt; [
        'callback' =&gt; '::addMore',
        'wrapper' =&gt; 'ajax_wrapper',
      ]
    ];

    return $form;
  }

  public function addMore(array &amp;$form, FormStateInterface $form_state){
    return $form;
  }

  public function submitForm(array &amp;$form, FormStateInterface $form_state){

  }