0

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' => 'textfield',
    '#title' => $this->t('Name'),
    '#maxlength' => 64,
    '#size' => 64,
    '#default_value' => $name,
);

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

$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..",
        ),
    ),
);

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

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

This is the callback function.

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

How do I add a new field after filling-up my Flat Per Floor field?

  • is flat per floor an optional field? or a required field? – No Sssweat May 19 '16 at 6:59
  • It will be required field. But I didn't add the required option. – Imran Sarder May 19 '16 at 7:04
  • then you could go with my answer here – No Sssweat May 19 '16 at 7:29
0

I don't have much experience in Drupal 8. Please refer my suggestion bellow.

  1. 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',
        ),
    );
    
  2. 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.