I have a Drupal form, but I am adding it to the page as the result of an AJAX callback.
I need this form to trigger a new callback. My code below:
$form['#suffix'] = '<div id="form-return-message-box">this is the return box</div>'; $form['#attached']['js'] = array('misc/ajax.js'); $form['markup'] = array( '#type' => 'markup', '#markup' => '<h2>This is a form</h2>' ); $form['button'] = array( '#type' => 'button', '#value' => t('Submit'), '#ajax' => array( 'callback' => 'module_myform_callback', 'wrapper' => 'form-return-message-box', 'method' => 'replace', 'effect' => 'fade', ), ); $replace_layer = '#somelayer'; $commands = array(); $commands = ajax_command_replace($replace_layer, drupal_render($form)); $page = array( '#type' => 'ajax', '#commands' => $commands, ); ajax_deliver($page);
So this is what happens: this form is being added into a container called 'somelayer' that already exists on the page (I didn't add that part of the code because I thought it would be unnecessary). It was called from a link with the class 'use-ajax'.
So the form renders on the page as desired after an AJAX callback triggered by the link. This part works allright.
But here is the (very) tricky part: I would also like to preserve the new form AJAX functionality (check the '#ajax' part of the array), which doesn't occur. After the form is rendered, the button won't trigger any AJAX code. By clicking on it, the page will refresh, not triggering the callback function (not added here to preserve space).
By looking into source code of a regular form page with AJAX, you will see code like this that enables the AJAX functionality:
By looking at the source code of the form added into my page, I can see there is no piece of
<script></script> code that would trigger the AJAX callback in my dynamically loaded form. How can I emulate all the AJAX functionality when the form is rendered after an AJAX callback?