Below given is the code for the creation and removal of the custom form field using Ajax in Drupal 8.
public function buildForm(array $form, FormStateInterface $form_state) { $form['#tree'] = true; $form['#prefix'] = ' '; $form['#suffix'] = ''; $form['#cache'] = ['max-age' => 0]; $nb_sponsee = $form_state->get('nb_sponsee'); $form['sponsees'] = [ '#type' => 'container', '#prefix' => ' ', '#suffix' => '', ]; $class ='member'; for ($i = 0; $i < $nb_sponsee; $i++) { $form['sponsees'][$i]['sponsee'] = [ '#type' => 'fieldset', '#title' => $this->t('Your Account'), ''#attributes' => [ 'class' => $class, ], ]; $form['sponsees'][$i]['sponsee']['firstname'] = [ '#prefix' => ' ', '#suffix' => '', '#type' => 'textfield', '#title' => $this->t('First Name'), '#placeholder' => $this->t('Firstname'), '#maxlength' => 64, '#size' => 64, '#required' => TRUE, ]; $form['sponsees'][$i]['sponsee']['last name'] = [ '#type' => 'textfield', '#title' => $this->t('Last Name'), '#placeholder' => $this->t('Last Name'), '#maxlength' => 64, '#size' => 64, '#required' => TRUE, ]; $form['sponsees'][$i]['sponsee']['dob'] = [ '#type' => 'date', '#title' => $this->t('Date Of Birth'), '#placeholder' => $this->t('Date Of Birth'), '#required'=> TRUE, ]; $form['sponsees'][$i]['sponsee']['email'] = [ '#type' => 'email', '#title' => $this->t('Email Address'), '#placeholder' => $this->t('Email Address'), '#required' => TRUE, ]; $form['sponsees'][$i]['sponsee']['phone'] = [ '#type' => 'textfield', '#title' => $this->t('Telephone Number'), '#placeholder' => $this->t('Telephone Number'), '#maxlength' => 64, '#size' => 64, '#disabled' => $disabled, ]; $form['sponsees'][$i]['sponsee']['street_house'] = [ '#type' => 'textfield', '#title' => $this->t('Street and House Number'), '#placeholder' => $this->t('Street and House Number'), '#maxlength' => 64, '#size' => 64, '#required' => TRUE, ]; $form['sponsees'][$i]['sponsee']['postal_code'] = [ '#type' => 'textfield', '#title' => $this->t('Postal Code'), '#placeholder' => $this->t('Postal Code'), '#maxlength' => 64, '#size' => 64, '#required' => TRUE, ]; $form['sponsees'][$i]['sponsee']['place'] = [ '#type' => 'textfield', '#title' => $this->t('Place'), '#placeholder' => $this->t('Place'), '#maxlength' => 64, '#size' => 64, '#required' => TRUE, ];