Reputation: 10847
I'm updating a module I've written from D6 to D7, and therefore have to exchange the old AHAH by the new #ajax in forms.
I'm performing an ajax request which creates a result and replaces a form element with it. This basically works fine, but after the first request, the result is cached and does not take changes in the form into account. I think this is probably a browser-issue, but could it be that Drupal sends an expiration header which induces the browser to take the cached version? Ot any other ideas?
The fragment in hook_cache():
$form['fieldset']['mybutton'] = array(
'#type' => 'button',
'#value' => t('Send request'),
'#ajax' => array(
'callback' => 'mycallback',
'wrapper' => 'mywrapper',
'method' => 'replace',
'effect' => 'fade',
)
A snippet of the callback:
function mycallback($form, $form_state) {
[..]
$form['fieldset']['mywrapper']['#markup'] = 'test';
return $form['fieldset']['mywrapper']['#markup'];
}
Upvotes: 2
Views: 3304
Reputation: 1393
Figured it out with help of the first answer
Add wrapper again
function mymodule_mycallback(&$form, &$form_state) {
$form['fieldset']['my_element']['#prefix'] = '<div id="mywrapper">';
$form['fieldset']['my_element']['#suffix'] = '</div>';
// Always, always, always return an element here, not a string.
// This makes sure the form state stays consistent.
return $form['fieldset']['my_element'];
}
And i don't think that u have to use the pointers (&) at least the drupal example module doesn't
Upvotes: 1
Reputation: 36955
I've run into this problem a few times and it isn't a caching issue. The problem is you'll originally have a <div>
wrapped around your mywrapper
element, but in your ajax callback you're replacing it with a string...the <div>
wrapper is therefore replace and next time you press the button the script can't find the <div>
it needs to replace as it's not there any more!
Also, the arguments for your mycallback
function need to be passed in by reference so change the signature to this: function mycallback(&$form, &$form_state) {
.
Try making your code look a bit more like this:
function mymodule_my_form($form, &$form_state) {
$form['fieldset'] = array(
'#type' => 'fieldset'
);
$form['fieldset']['my_element'] = array(
'#markup' => 'Some initial markup',
'#prefix' => '<div id="mywrapper">',
'#suffix' => '</div>'
);
$form['fieldset']['mybutton'] = array(
'#type' => 'button',
'#value' => t('Send request'),
'#ajax' => array(
'callback' => 'mymodule_mycallback',
'wrapper' => 'mywrapper',
'method' => 'replace',
'effect' => 'fade',
)
);
return $form;
}
function mymodule_mycallback(&$form, &$form_state) {
$form['fieldset']['my_element']['#markup'] = 'New Markup';
// Always, always, always return an element here, not a string.
// This makes sure the form state stays consistent.
return $form['fieldset']['my_element'];
}
If in doubt have a look at the examples module, specifically the ajax_example_submit_driven_ajax()
example in the ajax_example
module.
Upvotes: 10