Skip to main content
3 of 3
edited tags
avpaderno
  • 97.9k
  • 15
  • 164
  • 284

How to add new form field dynamically on selected change using ajax

I'm trying to make dynamic form in my module: I have one field of type select containing some options, and when selecting one option a new field should be added dynamically to the form which in turn will contain another list of options. here what I try to do but nothing seems to work correctly

public function buildForm(array $form, FormStateInterface $form_state) {
    $this->controller = new Place_AdsController();
    $terms = $this->controller->content();

    $form['#attached']['library'][] = 'Place_Ads/general';
    $form['level1'] = array(
        '#type' => 'select',
        '#description' => 'Please select level one term',
        '#options' => $terms,
        '#attributes' => array(
            'class' => array(
                'mycategory'
            ),
        ),
        '#ajax' => array(
            // Function to call when event on form element triggered.
            'callback' => 'Drupal\Place_Ads\Form\Place_AdsForm::level1SelectedCallback',
            // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
            'effect' => 'fade',
            // Javascript event to trigger Ajax. Currently for: 'onchange'.
            'event' => 'change',
            'progress' => array(
                // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
                'type' => 'throbber',
                // Message to show along progress graphic. Default: 'Please wait...'.
                'message' => NULL,
            ),
        ),
    );
    return $form;
}
public function level1SelectedCallback(array &$form, FormStateInterface $form_state) {
    // Instantiate an AjaxResponse Object to return.
    $ajax_response = new AjaxResponse();
    if ($form_state->getValue('level1') != false) {
        $form['level2'] = array(
            '#type' => 'select',
            '#description' => 'Please select level two term',
            //'#options' => $terms,
            '#attributes' => array(
                'class' => array(
                    'mycategory'
                ),
            ),
        );
        $form_state->setRebuild(TRUE);
    }
    
    return $ajax_response;
}