Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By dalahimself on
I have a prolem when submitting a form.
The code is basically built up like this:
function myform(){
.......(make the form).....
return $form;
}
function myform_submit($form, &$form_state){
drupal_set_message(t('The settings have been saved'));
}
function myformpage(){
return drupal_get_form('myform');
}
A link to the formpage is added using hook_menu:
function mymodule_menu(){
$items['mymodule/myformpage'] = array(
'title' => 'Myform',
'page callback' => 'myformpage',
'type' => MENU_NORMAL_ITEM, //Will appear in Navigation menu.
);
}
When the user submits the form first myformpage() gets called, then myform_submit($form, &$form_state) gets called and then myformpage() gets called one more time.
Why is myformpage() called twice?
And how can I prevent this?
Comments
I would do it like this
I think that function is called again because the 'action' attribute of the form tag is the same page. so the menu hook is called again.
Actually, the fuction
Actually, the fuction myformpage() does a couple of things before generating the form and passes a couple of parameters to myform(), so the form is generated a little differently depending on the parameters. The code is more like this:
Thats why I set myformpage() as the callback instead of calling drupal_get_form() directly...
Fixed it!
Put this in myform_submit($form, &$form_state):
$form_state['redirect']=FALSE;
It seems Drupal automatically redirects after processing the form, and the default redirect page is the same page. Thats why my callback got called twice. By setting $form_state['redirect'] to FALSE the redirection is disabled.
So where is it redirected instead?
So where is it redirected instead?
Its not redirected
Its not redirected anywhere.
My callback function calls drupal_get_form and I want to display the form generated by my callback. I don't want to get redirected after my callback has generated the form. That was my whole problem...
sure but
once you submit the form it is redirected somewhere, isn't it?
the form has 'action' attribute.
The form executes my
The form executes my callback; thats the function which gets called in the link provided by the forms "action" attribute.
However, after the callback has completed, Drupal seems to redirect to another page. I guess the idea is that the callback function shouldn't really display anything, it should just do things "behind the scenes", like storing stuff in a database and setting messages using drupal_set_message(), for example. Then, after the callback completes, Drupal redirects to a displayable page.
My issue was that my callback actually displays the data, therefore I didn't want Drupal to redirect anywhere after the callback was called.