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' => 'fieldset', '#title' => $this->t('People coming to picnic'), '#prefix' => '<div id="names-fieldset-wrapper">', '#suffix' => '</div>', '#attributes' => array('class'=>array('container-inline')), ]; for ($i = 0; $i < $num_names; $i++) { $form['names_fieldset']['fields'][$i] = [ '#type' => 'fieldset', '#name' => 'id_'.$i ]; $form['names_fieldset']['fields'][$i]['ids'] = [ '#type' => 'textfield', '#title' => $this->t('ID'), '#default_value' => $i, '#name' => 'id_'.$i ]; $form['names_fieldset']['fields'][$i]['name'] = [ '#type' => 'textfield', '#title' => $this->t('Name') ]; $form['names_fieldset']['fields'][$i]['remove'] = [ '#type' => 'submit', '#name' => 'remove_'.$i, '#value' => $this->t('Remove this'), '#submit' => ['::removethisCallback'], '#ajax' => [ 'callback' => '::addmoreCallback', 'wrapper' => '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 &$form, FormStateInterface $form_state) { $button_clicked = $form_state->getTriggeringElement()['#name']; $id = substr($button_clicked,7); $values = $form_state->getValue(['names_fieldset']); unset($values[$id]); $form_state->setValues(['names_fieldset'], array_values($values)); $name_field = $form_state->get('num_names'); if ($name_field > 1) { $remove_button = $name_field - 1; $form_state->set('num_names', $remove_button); } $form_state->setRebuild(); }
But It doesn’t work. How could I remove or update an item from $form_state?