Remove an item from $form_state in an ajax callback I'm using this form api example: AjaxAddMore. I want to add a "remove button" for each indiviaul element, in order to remove an item but not the latest. Thouse are my changes:  

...
  $form['names_fieldset'] = [
      '#type' =&gt; 'fieldset',
      '#title' =&gt; $this-&gt;t('People coming to picnic'),
      '#prefix' =&gt; '&lt;div id="names-fieldset-wrapper"&gt;',
      '#suffix' =&gt; '&lt;/div&gt;',
      '#attributes' =&gt; array('class'=&gt;array('container-inline')),
    ];

    for ($i = 0; $i &lt; $num_names; $i++) {

      $form['names_fieldset']['fields'][$i] = [
        '#type' =&gt; 'fieldset',
        '#name' =&gt; 'id_'.$i
      ];

      $form['names_fieldset']['fields'][$i]['ids'] = [
        '#type' =&gt; 'textfield',
        '#title' =&gt; $this-&gt;t('ID'),
        '#default_value' =&gt; $i,
        '#name' =&gt; 'id_'.$i
      ];

      $form['names_fieldset']['fields'][$i]['name'] = [
        '#type' =&gt; 'textfield',
        '#title' =&gt; $this-&gt;t('Name')
      ];

      $form['names_fieldset']['fields'][$i]['remove'] = [
        '#type' =&gt; 'submit',
        '#name' =&gt; 'remove_'.$i,
        '#value' =&gt; $this-&gt;t('Remove this'),
        '#submit' =&gt; ['::removethisCallback'],
        '#ajax' =&gt; [
          'callback' =&gt; '::addmoreCallback',
          'wrapper' =&gt; 'names-fieldset-wrapper',
        ],
      ];
    }
....


It works good and I can add several records. But I can't remove an item other than the latest one. This is my callback function where I've tried to unset the item I want to remove:

public function removethisCallback(array &amp;$form, FormStateInterface $form_state) {
    $button_clicked = $form_state-&gt;getTriggeringElement()['#name'];
    $id = substr($button_clicked,7);
    $values = $form_state-&gt;getValue(['names_fieldset']);
    unset($values[$id]);
    $form_state-&gt;setValues(['names_fieldset'], array_values($values));  

    $name_field = $form_state-&gt;get('num_names');
    if ($name_field &gt; 1) {
        $remove_button = $name_field - 1;
        $form_state-&gt;set('num_names', $remove_button);
    }   
    $form_state-&gt;setRebuild();
}


But It doesn't work. How could I remove or update an item from $form_state?
$form_state->setValues(['names_fieldset'], array_values($values));


setValues(array $values) only has 1 parameter

For 2 params, you need to use setValue($key, $value) without the "s"

$form_state-&gt;setValue('name', array_values($values));  




Alternatively, you could do

$values = $form_state-&gt;getValues();
$values['name'] = array_values($values);
$form_state-&gt;setValues($values);