How do I conditionally add a field? I'm trying to find out any example of adding new conditional field using ajax in Drupal 8 form API, but I can't find it.

This is my code.

$form['name'] = array(
    '#type' =&gt; 'textfield',
    '#title' =&gt; $this-&gt;t('Name'),
    '#maxlength' =&gt; 64,
    '#size' =&gt; 64,
    '#default_value' =&gt; $name,
);

$form['floor'] = array(
    '#type' =&gt; 'textfield',
    '#title' =&gt; $this-&gt;t('Floor'),
    '#default_value' =&gt; $floor,
);

$form['flat_per_floor'] = array(
    '#type' =&gt; 'textfield',
    '#title' =&gt; $this-&gt;t('Flat Per Floor'),
    '#default_value' =&gt; $flatPerFloor,
    '#ajax' =&gt; array(
        'callback' =&gt; 'Drupal\bms_flat\Form\FlatForm::flatGenerate',
        'effect' =&gt; 'fade',
        'event' =&gt; 'change',
        'method' =&gt; 'replace',
        'progress' =&gt; array(
            'type' =&gt; 'throbber',
            'message' =&gt; "Generating..",
        ),
    ),
);

if ($form_values['floor']) {
  $form['flats'] = array(
    '#type' =&gt; 'checkboxes',
    '#title' =&gt; $this-&gt;t('Content Type'),
    '#options' =&gt; node_type_get_names(),
  );
}

$form['submit'] = array(
    '#type' =&gt; 'submit',
    '#title' =&gt; $this-&gt;t('Submit'),
    '#default_value' =&gt; $this-&gt;t($submit),
);


This is the callback function.

public function flatGenerate(array &amp;$form, FormStateInterface $form_state) {
  // …
}


How do I add a new field after filling-up my Flat Per Floor field?
I don't have much experience in Drupal 8. Please refer my suggestion bellow.


Please add wrapper item for the ajax call
eg:  


$form['flat_per_floor'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Flat Per Floor'),
    '#default_value' => $flatPerFloor,
    '#ajax' => array(
        'callback' => 'Drupal\bms_flat\Form\FlatForm::flatGenerate',
        'effect' => 'fade',
        'event' => 'change',
        'method' => 'replace',
        'progress' => array(
            'type' => 'throbber',
            'message' => "Generating..",
        ),
        'wrapper' => 'flat-per-floor-wrapper',
    ),
);

Add the wrapper container under the flat_per_floor field

 
$form['flat_per_floor_wrapper'] =  array(
  '#type' => 'container',
  '#attributes' => ['id' => 'flat-per-floor-wrapper']
);
 

For more details please refer the example module for drupal 8 and check the ajax form
https://www.drupal.org/project/examples