I have a form with a button that when pressed re-builds a different part of the form via an ajax request.
Upon clicking the button the form is rebuilt, then my ajax callback is called which saves the values from the form, and then returns part of the form.
The problem is the form is rebuilt BEFORE my callback which saves the values, and therefor alters how the form is built.
If I click the ajax button a second time then it works correctly as has the values from the previous ajax request when the form is build.
How can I get my callback function to run before the form is rebuilt?
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_ajax_submit'),
'#value' => 'Save',
'#ajax' => array(
'callback' => 'emtr_shift_plan_form_ajax_submit',
'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
}
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
return $form['positions'];
}
EDIT:
As a workaround I found it is possible to manually rebuild the form a second time in the ajax callback with $form = drupal_rebuild_form('emtr_shift_plan_form', $form_state);
, but is seems inefficient building the form twice. Can I just swap the order of these events over as opposed to having the build the form twice per ajax request?