The following code puts up a simple form correctly, but when I press 'submit', the page just refreshes instead of executing the code in the _submit function. What have I done wrong? (I'm running Drupal 5.1)

  $output = drupal_get_form('my_function');
  echo "$output";

  function my_function() {
        $form['test'] = array (
              '#type' => 'fieldset',
              '#title' => t('testing...'),
        );
        $form['test']['param'] = array (
              '#type' => 'textfield',
              '#title' => t('my param'),
        );
        return $form;
  }

  function test_submit($form_id,$form_values) {
        ...
  }

Comments

nevets’s picture

By default if your form function is 'my_function', the submit function should be 'my_function_submit'.

blond_and_stupid’s picture

Thanks, I'm aware of that. I wrote a test script that calculates your Body Mass Index. It does not work either for the same reason. After clicking the submit button, the script just seems to refresh the page without entering the submit function. I'm very grateful if someone can point out what I'm doing wrong!

<?php


  $output = drupal_get_form('bmi');
  echo "$output";

  function bmi() {

        $form['bmi'] = array (
              '#type' => 'fieldset',
              '#title' => t('Calculate BMI'),
        );

        $form['bmi']['length'] = array (
              '#type' => 'textfield',
              '#size' => 5,
              '#title' => t('length (cm)'),
              '#prefix' => '<table><tr><td width="100">',
              '#suffix' => '</td>',
        );

        $form['bmi']['weight'] = array (
              '#type' => 'textfield',
              '#size' => 5,
              '#title' => t('weight (kg)'),
              '#prefix' => '<td>',
              '#suffix' => '</td></table>',
        );

        $form['submit'] = array (
              '#type' => 'submit',
              '#value' => t('Go'),
        );

        return $form;
  }

  function bmi_submit($form_id,$form_values) {

        $l = $form_values['length'];
        $w = $form_values['weight'];
        $bmi = round(10000*$w/($l*$l));
        echo "Your BMI: $bmi<br />";
  }

?>

nevets’s picture

From the code I suspect you placed this in a node in which case it will not work as 'bmi_submit' does not exist except when the page is being used. Normally the form api is used from within a module.

criznach’s picture

Remember that forms always redirect after submission unless the redirect flag is set to false. So your "echo" statement is never seen. Change your "echo" to "drupal_set_message()" and it should be displayed after the redirect.

Chris.

http://www.trailheadinteractive.com
--- Featured Projects ---
http://www.montanakitesports.com
http://www.cmrussell.org
http://www.tdandh.com
http://www.cccsmt.org
http://www.universalsemensales.com

depace’s picture

i have a similar problem with the form submit..

i have a function as tasks_create_grid_form, theme_tasks_create_grid_form, tasks_create_grid_form_validate and tasks_create_grid_form_submit

upto validate everything works fine but after that it never calls _submit function.. what might be the problem??

function tasks_create_grid_form()
{
$arr_form['task_name_1']	=	array(
												'#type'=>'textfield',
												'#required'=>false,
												'#size'=>35,
												'#maxlength'=>50);
}

function tasks_create_grid_form_submit($form, $form_values)
{
drupal_set_message(t('Problem...'));
}

i'm using this inside a module as well.. so the _submit has to be called

depace’s picture

use type as submit instead of 'button' :-)

queenielow’s picture

Hi,

I'm creating a new module and i've done the layout of the form and i want to submit the values so i can get it saved.
After i press submit button, it just refresh my screen on to the same page.

Please help me .. let me know where i did wrong..

Thanks

function kit_form() {
$heading_title="TEST on Submit";

 // Heading
  $form['kitnonschool']['heading_title']= array(
    '#type' => 'fieldset',
    //'#title' => t('Describe it'),
    //'#default_value' =>  variable_get('description', ''),
	//'#default_value'=>'TEST',
    //'#cols' => 60,
    //'#rows' => 2,
    '#description' => t($heading_title),
  );
	
 //Personal Details
 $pd="<h2>Personal Details</h2>";
   $form['kitnonschool']['pd_title']= array(
    '#type' => 'fieldset',
    //'#title' => t('Describe it'),
    //'#default_value' =>  variable_get('description', ''),
	//'#default_value'=>'TEST',
    //'#cols' => 60,
    //'#rows' => 2,
    '#description' => t($pd),
  );
  
 $form['kitnonschool']['email_add'] = array('#type' => 'textfield',
    '#title' => t('Email Address'),
    '#default_value' => ('Email Address'),
	'#required' => TRUE,
    //'#description' => t('Optional auto-reply. Leave empty if you do not want to send the user an auto-reply message.'),
  );

 $form['kitnonschool']['county'] = array(
   '#type' => 'select',
   '#title' => t('County'),
   '#options' => array(db()),
  // '#default_value' => variable_get('kitnonschool', array('0 Cost Codes')),
	//'#description' => t('A text field will be available on these node types to make user-specific notes.'),
);


 $form['kitnonschool']['submit'] = array(
 '#type' => 'submit',
 '#value' => t('submit'),
  
);   

return $form;
}


function kit_submit($form_id, $form_values) {
  //db_query("INSERT INTO {table} (name, log, hidden) VALUES ('%s', %d, '%s')", $form_values['name'], $form_values['access']['log'],  $form_values['hidden']);
  drupal_set_message(t('Your form has been saved.'));
  echo $form_values['kitnonschool']['county'];
}
queenielow’s picture

i added " '#redirect' => drupal_get_form('kit_submit')," to make it call my submit function. and i also change to use $_POST for the value..

 $form['submit'] = array(
 '#type' => 'submit',
 '#value' => t('submit'),
 '#redirect' => drupal_get_form('kit_submit'),
 );   

function kit_submit() {
  //db_query("INSERT INTO {table} (name, log, hidden) VALUES ('%s', %d, '%s')", $form_values['name'],$form_values['access']['log'],  $form_values['hidden']);
  drupal_set_message(t('Your form has been saved.'));
  drupal_set_message($_POST['email_add']);
}
nevets’s picture

It is not the best idea to use $_POST directly as it bypasses some of the features of the form API.

You do not show how you are invoking the form in your example but I am guessing it looks like

drupal_get_form('kit_form'),

in which case your submit function would be called 'kit_form_submit'.

ilo’s picture

about api compliant names!

if form's name is:

function kit_form()

then the submit for SHOULD BE:

function kit_form_submit (
queenielow’s picture

Hi nevets,

yeah i using drupal_get_form('kit_form').

Hi ilo,

Thanks so much.. now i know why it didnt work in the 1st place.. coz my function name..

Thanks alot guys,
Queenie

jochenh’s picture

I am also unable to get form_submit working right. In my module nodes are validated regarding some custom properties using a call to hook_nodeapi | case 'submit'. After a node is submitted and processed a custom error message is displayed back to the user which includes a form (using a call to:

$message = "some instructions and " . drupal_get_form('myform', $node);
return $message;

Then I have the following functions:

function myform($node) {
// builds the form with a textfield and

$form['myform']['submit'] = array(
		'#type' => 'submit',
		'#value' => t('submit form'),
		);

return $form;
}

All that works fine but it seems that my call to 'submit' is never reached:

function myform_submit($form_id, $form_values) {
//execute some database code and display a message
drupal_set_message('all done');
}

I have no idea why this is happening and have read through all the postings I could find. I believe my code is properly constructed and I am following the correct FAPI names. Could this have to do with the fact that the form is constructed after nodeapi / submit has been called?

Any help is greatly appreciated
Thanks
- j

nevets’s picture

In what context does

<?php
$message = "some instructions and " . drupal_get_form('myform', $node);
return $message;
?>

run? What actual displays the message?

And is this really an "error" message? By the time you reach the node be submitted it is a bit late for errors (should be done during validation),

And as always, a URL showing the form in action would be useful (saves a lot of guessing)

jochenh’s picture

hi,

thanks for replying on this ! I ended up changing my code. Perhaps I was trying to do something impossible. My site did this:

* create a custom event that contains some cck fields
* prior to event submission (node_api), check for conflicts with other events
* if conflicts, show event, after it has been saved and display some messages

So ideally I wanted to show the form right after the messages and allow users to make notes about the event that has just been submitted and then submit that form. The form itself only updates a piece of CCK content on the event...

Is that totally backwards?

I have figured out an alternative option, by just redirecting them to a separate page on the node which contains a menu to submit the form...

Thanks
- j

nevets’s picture

If I understand correctly someone adds a new event and when they submit the event you check to see if it conflicts with any existing events.

If the event conflicts you want to display a form (which contains a message) so they can if they wish add a note to the other event.

By default after submitting the event you will be placed on the page showing the new event. Is this the behaviour you want?

Do you want the message/form above or below the new event?

Have you though about what happens if there is more than one event that already conflicts? (this makes displaying the form somewhat more challanging).

jochenh’s picture

hi,

yes that is the plan for now. I am still adding some final touches to my code to handle conflicts on repeating events and multiple event conflicts... If there are multiple conflicts each one will be displayed in sequence, but the user still has 1 form at the end of that sequence to put in his or her comments...
- j

sumgai’s picture

I have problems with forms that don't use a "submit" button to submit the form.

In one case, I have several buttons that are all '#type' => submit. In the other case, there are some hyperlinks in the form that call some javascript that eventually does a <form-name>.submit().

The form's validate function is called, but the submit function is never called -- even if it validates correctly. I'm returned to the form, with the fields filled in (the form's build function is called on submit as well as the validate function), but none of the form's submit actions are done.

I've traced it through with PhpED's debugger but didn't go into the bowels of the form.inc code.

Is there something I need to set so the form module processes these "different" submits as real submits?

Thanks,

m

bogeymin’s picture

But I had a problem similar to this as well. I wanted to create a one-field autocomplete form with no submit button, but apparently drupal requires the submit button. My work around was to create the submit element as usual but add #attributes => array('style' => 'display: none') to the element. It now calls both the submit and validate hooks.

palomma612’s picture

<script type="text/javascript" language="javascript">


<!--
function validate(){
if (!document.survey.name.value){ 
alert ("You must enter your name before submitting this form.");
document.survey.name.focus();
return false;
}




if(!document.survey.lastname.value){
alert ("You must enter your lastname before submitting this form.");
document.survey.lastname.focus();
return false;
}

if(!document.survey.address.value){
alert ("You must enter your Address before submitting this form.");
document.survey.address.focus();
return false;
}

if(!document.survey.city.value){
alert ("You must enter your City before submitting this form.");
document.survey.city.focus();
return false;
}

if(!document.survey.state.value){
alert ("You must enter your State before submitting this form.");
document.survey.state.focus();
return false;
}



if  (!document.survey.cellnum.value){
alert ("You must enter your cell number before submitting this form.");
document.survey.cellnum.focus();
return false;
}else{
return true;
}

}

function validatemail(){
    var theEmail = document.survey.email.value;
    var atLoc = theEmail.indexOf("@",1);
    var dotLoc = theEmail.indexOf(".",atLoc+2);
    var len = theEmail.length;
    if (atLoc > 0 && dotLoc > 0 && len > dotLoc+2){
        return true;
    }else{
        alert("Please enter your e-mail address properly.");
        document.survey.email.focus();
        return false;
    }   
}

function checkNumber() {
num=document.form[0].zipcode.value;
alert("Data you Entered: "+ num);
if (isNaN(num)) {
alert("You must enter a number for the zip code. Please resubmit."); 
} // end if
return false;	
} //end fun

//-->
</script>
</head>

<body bgcolor="#FFFFCC">
<h1><font face="Verdana" color="#990066">Customer Registration Form</h1></font>
<hr color="#FF6600"/></hr>

<form action="mailto:rmaldonado508@pccc.mailcruiser.com"
method="POST" enctype="text/plain" name="survey"
onsubmit="return validate();validatemail();return checkNumber();">

<font face="verdana">

<h5><b>*All Information is required*</b></h5>
<br><br /></br>

Name:  <input type="text" size="20" name="name" value="">  
LastName:  <input type="text" size="25" name="lastname" value="">
<br><br /></br>

Address:  <input type="text" size="20" name="address" value="">
City: <input type="text" size="10" name="city" value=""> 
 State: <input type="text" size="2" name="state" value="" maxlength="2"> 
  ZipCode:  <input name="zipcode" type="text" size="5" maxlength="5"> 
<br><br /></br> 
Cell Phone Number:<input type="text" name="cellnum" value="" size="10" /></p>
<br><br /></br> 

E-Mail:  <input size="60" name="email"><br><br /></br> 


<p><input type="submit" value="Submit" />
</p>

</font>
</form>
</body>
</html>

[Edited to add <code> and </code> tags; nevets]

nevets’s picture

If this is a real request for support a) it should have been posted as new issue, b) you need to state the problem you are having. Note that your form is completely non-standard as Drupal forms go so it might help if you stated what you are trying to achieve.

huangweiqiu’s picture

I got a same problem,but I fixed it by guided this post:

http://www.ubercart.org/forum/development/3949/after_theme_form_tapir_dr...

the problem is due to form theming.
"

I think in themeing forms you need to output:
drupal_render($form);
at the end of your form.

Just try inserting that at the end of your theme function. It does some sort of voodoo and tells the magic form pixies to make the form work.
I've never fully understood it.

So try:
function remove_theme_tapirtest_example_6_form($form) {
$output = '

'. tapir_get_table('tapirtest_example_table_6', $form)
. drupal_render($form['submit']) .'

';
$output .= drupal_render($form);
return $output;
}
"

I added " $output .= drupal_render($form['form_id']);
$output .= drupal_render($form['form_token']);" above "return $output",then it works!