2

I am trying to insert new form fields into exiting wrapper within ajax callback function.

I succeeded doing so, but trying to get those new fields values inside submit function failed because they are listed in the form state values array.

How can I make their values available to be used inside the submit function.

$form['test'] = array(
        '#type' => 'select',
        '#options' => array('- Please select -' => [1=>'one',2=>'two']),
        '#ajax' => array(
            'callback' => '::testSelectedCallback',
            'wrapper' => 'fields-wrapper',
            'effect' => 'fade',
            'event' => 'change',
            'progress' => array(
                'type' => 'throbber',
                'message' => NULL,
            ),
        ),
    );
$form['fields-wrapper'] = array(
        '#type' => 'container',
        '#attributes' => ['id' => 'fields-wrapper', 'class' => ['hiddenselect']],
    );

public function testSelectedCallback(array &$form, FormStateInterface $form_state) {
$form['fields-wrapper']['new_item']= array(
'#type' => 'textfield',
'#title' => 'My new item',
);
$form_state->setRebuild(True);
return $form['new_item'];
}

1 Answer 1

3

You cannot add fields in ajax callback functions - assuming that level2SelectedCallback() is your ajax callback (you named it something different in your form element defintion).

All form elements need to be added in the form definition. The ajax callback is only used for determining which elements need to be inserted into the page when the AJAX is returned.

7
  • never mind the name, actually I don't know the form fields type until I reach the callback sp for that reason I put the new fields inside the ajax callback Commented Sep 29, 2016 at 7:05
  • Regardless, it won't work. The form has been cached by that point, and anything not part of the cache is ignored, and on D7 at least throws an error about an 'illegal option' (not sure if the error still shows in D8 or not). You can determine which fields to show after your ajax call in the form definition, by checking submitted values in $form_state['values']
    – Jaypan
    Commented Sep 29, 2016 at 7:08
  • Correct. An ajax callback will rebuild the form, you need to define it differently there and then return the new part in the ajax callback.
    – Berdir
    Commented Sep 29, 2016 at 8:11
  • so is there a way to define generic form element in the form build, so its type can be decided in the ajax callback?? Commented Sep 29, 2016 at 18:36
  • No, as the element will already be cached, and so cannot be altered. How is the type being determined between the form definition and the AJAX callback?
    – Jaypan
    Commented Sep 29, 2016 at 22:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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