Drupal - Rebuild form AFTER ajax callback has run
You could try like this making submit different and callback different and see if it helps.
$form['save'] = array(
'#type' => 'button',
'#submit' => array('emtr_shift_plan_form_ajax_submit'),
'#value' => 'Save',
'#ajax' => array(
'callback' => 'emtr_shift_plan_form_ajax',
'wrapper' => 'postions',
),
'#id' => 'ajax-save-form-values',
);
function emtr_shift_plan_form_ajax($form, &$form_state){
return $form['positions'];
}
function emtr_shift_plan_form_ajax_submit($form, &$form_state) {
ddl('ajax submit'); // log the ajax callback is being called
$form_state['rebuild'] = TRUE; // As the form has already been rebuilt at this point what effect can this have?!?
emtr_shift_plan_form_save($form, $form_state); // save the values
// This is the point at which I want the form to be rebuilt
}
I know this question is 3 years old, but I came upon it while searching for a similar issue.
You'll need to modify your approach to get this working. The order of operations when you submit the AJAX request is this:
- AJAX submit callback is fired. In your AJAX submit callback you'll want to save the data. Flag it in your
$form_state
variable. - Form is rebuilt.
- AJAX callback is fired.
I've re-worked your code a little bit to demonstrate.
// AJAX FLOW: 2. Form rebuild is fired.
function emtr_shift_plan_form($form, &$form_state) {
ddl('build'); // log that this function is being called
$form['save'] = array(
'#type' => 'button',
'#submit' => array('emtr_shift_plan_form_button_submit'),
'#value' => 'Save',
'#ajax' => array(
'callback' => 'emtr_shift_plan_form_ajax',
'wrapper' => 'postions',
),
'#id' => 'ajax-save-form-values',
);
$form['postions'] = array(
'#type' => ' container',
'#prefix' => '<div id="postions">',
'#suffix' => '</div>',
);
// code here to populate the positions container
if (isset($form_state['saved_values'])) {
// do stuff.
}
}
// AJAX FLOW: 1. Button submit is fired.
function emtr_shift_plan_form_button_submit($form, &$form_state) {
// log the ajax callback is being called
ddl('ajax submit');
// save the values. Make sure the data is stored somehow so your form can get at it.
$form_state['saved_values'] = emtr_shift_plan_form_save($form, $form_state);
// rebuild flag here will trigger emtr_shift_plan_form() to be run
$form_state['rebuild'] = TRUE;
}
// AJAX FLOW: 3. Button callback is fired.
function emtr_shift_plan_form_ajax($form, &$form_state) {
return $form['positions'];
}
Hope that sheds some light for someone.