I am a newbie in drupal module development. I created a form using form api. Now i want to get all the posted argument and query database with these arguments. And at last i want to show query results.

Please guide me how can i do this

Many thanks in advance

Comments

neil.sonaron’s picture

You mean
once you have filled your field and send them to server with submit button, you want to "view" your content?
If yes then take a look at hook_load, who is responsible to load the content of your nodes, and maybe hook_view to render your node on your own way or use a template file.

haroon373’s picture

Thank you very much neil.sonaron for considering my question.

But i am at the very beginning stage where i can't understand typical terms.

Let me explain more of my question.

I created a custom module for custom advance search. this search will work for specific content type.

My cutom module using these functions.

1. advsearch_menu() // to link my module
2. advsearch_page() // to display form on page.
3. advsearch_form() //to create the form
4. advsearch_form_validate($form, &$form_state) // validating form
5. advsearch_form_submit($form, &$form_state) //submit form

I just walk through a tutorial to do this.

After this, i want to query the database with all arguments posted by form, and at last display the result of the query in tables or whatever.

now please tell me what function will do this for me...?
Is there any need to create new custom module to show the data?
or i can show data in my same current custom module and wipe out (hide) the form.

Just like in conventional php programming

if($_POST['submit']) {
   //some functoins
} else {
   echo '<form name=""';
}

I hope I succeeded to explain my question...

Please take a look again.

cbearhoney’s picture

Did you ever get an answer to your question? If so, please post.

joeycbulk’s picture

The structure for form genaration function is:

function mymodule_form($form_state){
    // some code
    return $form;
}

The name of the function is to be passed on drupal_get_form() function (e.g. drupal_get_form('mymodule_form') ).

$form_state is an array where the key 'post' contains the array of post values.

Example:

function mymodule_form($form_state){
    /* check if user has submitted form */
    if(count($form_state['post']) == 0){
        /* create form elements if not yet submitted */
        /* imagine <input name="name" type="text" /> */
        $form['name'] = array(
            '#type' => 'textfield',
            '#title' => 'What is your name?',
            '#required' => true
        );
        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => 'Submit'
        );
    }else{
        /* display result if form has been submitted */
        /* 
         * $form_state['post']['name'] in drupal 
         * is like $_POST['name'] in regular php programming
         */
        $form['result'] = array(
            "#value" => 'Hi ' . $form_state['post']['name'] . '!<br />' . l('back','mymodule')
        ); /* OR do a db_query and place result */
    }
    return $form;
}
IS_NUMERIC’s picture

I'm having some problems with this.

Please review my code and explain how to output results back to the page.

Its a single text field which searches through a table and returns a single result (Or that's what I would like it to do).

The form displays and it looks like its submitting but is not firing the submit function


//////////////////////////////////////////////////////////
// Implementation of hook_menu()
function engineers_menu() {

  $items = array();

  $items['engineers'] = array(
                    'title' => 'Engineers',
                    'page callback' => 'engineers_form',
                    'access arguments' => array('access content'),
                    'type'=> true,
                      );
  return $items;

}

/////////////////////////////////////////////////////////
/// get form ////////////////////////////////////////////
function engineers_form(){

   $output = t('test test test');

   $output .= drupal_get_form('engineers_formfields');

   return $output;

}

//////////////////////////////////////////////////////////
// form fields ///////////////////////////////////////////
function engineers_formfields(){

        $form = array();

        $form['engineers'] = array(

                        '#type'=>'fieldset',
                        '#access'=>user_access('administer nodes'),
                        '#title'=> t('Search Engineers'),
                        '#collapsible'=> true,
                        '#collapsed'=> false,
                        '#tree'=>false,
        );

        $form['engineers']['search'] = array(
                        '#type' => 'textfield',
                        '#title' => t('Search for Engineers'),
                        '#size' => 60,
                        '#maxlength' => 128,
                        '#required' => true,
        );

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

    return $form;
    
}

//////////////////////////////////////////////////////////
// submitter which is not firing
function engineers_submit($form, &$form_state) {

    $val= $form_state['values']['search'];

    $query   = db_query("select * from {engineer_table} where {engineer_id}='%s'",$val);

       while($result = db_fetch_array($query)){

           $output .= $result['engineer_name']." | ".$result['engineer_id'];
           $output .= " <br/> ";

       }
       
      if (isset($query)) {

            drupal_set_message(t('Search submitted successfully.'));
        
       }else { 
       
            drupal_set_message(t('There was an error. Please try again.'));
           
       }

  return $output;
 
}
quiet’s picture

On the bright side (for me) its nice to know I'm not the only one having issues displaying results from a form submission.

In my case, the _submit function definitely runs... if I do a "print $output;" from there it prints the string to a blank page with my correct query results. My code is very similar to IS_NUMERIC's.

If I just leave it "return $output;" it ignores it and re-displays my original form.

I was expecting it to print the $output string (built successfully using the query results) in the main content block like the form does (basically replacing the form with the output string)... but it doesn't. Pretty sure I'm missing something very basic.

Any suggestions would be really appreciated.

===================
Edited to add:
I have some success using joeycbulk's method above doing the query processing in the hook_form function rather than hook_submit but it looks like $form_state['values'] isn't available in the _form hook function?? but $form_state['post'] is. Shouldn't I be able to return data from the hook_submit function where $form_state['values'] *is* available... Pretty much like IS_NUMERIC is trying to do?

The form builder type "value" (for other newbies thats sort of like a hidden field but not rendered to the form) isn't being passed in $form_state['post'] and I'd really like to use it like I can with $form_state['values'] in the _submit function.

Any suggestions would still be really appreciated. ;)

lorinpda’s picture

Hi,
I have a simple "proof of concept" module located here. It's a simple module that demonstrates an add form, validation and submit handlers, and a report page.

The user submits the add form, if valid , the system displays the report page (which includes the newly added value).

quiet’s picture

Thanks for the link and the time/comments. What you are doing makes perfect sense.

What I was hoping to do... what I expected I'd be able to do is use the submit function (or a call to another function from _submit) to produce the report... rather than redirect to another page. I'll do the redirect if that's what is necessary but it seems that I should be able to get that $output string back into the _form function (into $form['result'] or something)... no? Hmmm.... Or maybe the callback function that calls drupal_get_form since drupal_get_form looks like it resets some values (like "submitted").... I'll have to play with that.

It seems to me that this would be a more common topic. ;) Also, I found this --> http://www.lullabot.com/articles/drupal-5-making-forms-that-display-thei... (for D5) but that's still driving the work from _form.

I'm sure in the end I'll be doing it the way you suggest. ;) Thanks again!

Edited to add:
This method -> http://www.ferolen.com/blog/how-to-create-multistep-form-in-drupal-6-tut... leads me to what I wanted to do but in the "else" statement of _myform I assigned $form['result'] to "$form_state['storage']['results']" where I dumped $output to in the _submit function. Hope this helps anyone else traveling this road or at least doesn't lead them further astray!

Something like this:

function mysearch_form( $form_state, $search_type ) {
// passing in $search_type for further development with "do_search_type"

    if (empty($form_state['storage']['values'])) {
        // searching an external database triggered to search zipcodes
        // do_search_type held but not rendered to the form
        $form['do_search_type'] = array(
             '#type' => 'value',
             '#value' => 'zip',
        );
        // Create a fieldset for the body:
        $form['criteria'] = array(
             '#type' => 'fieldset',
             '#title' => t('Zip Code Search'),
        );
        $form['criteria']['zips'] = array(
             '#type' => 'textfield',
             '#title' => t('Enter Multiple Zip Codes'),
             '#size' => 50,
             '#maxlengh' => 255,
             '#description' => t('Zip code entry area.'),
        );
        $form['submit'] = array(
             '#type' => 'submit',
             '#value' => t('SEARCH'),
        );
    }else{
        $form['result'] = array(
            "#value" => $form_state['storage']['results'] ,
        ); 
    }
     return $form;
}

function mysearch_form_submit ( $form, &$form_state ) {
     // This is a pretty stripped down version without any value checking and such
     // and is a trimmed down, renamed and hacked up version of actual code (hopefully works as shown)
     $form_state['storage']['values'] = $form_state['values'] ;

     // mysearch_results function (not shown) does the DB work.. switches to external database
     // to run the query, switches back to the default db, formats output, etc
     $output = mysearch_results( $form_state['values'] ) ;

     // could have skipped "$output" and assigned directly to storage value above
     // but since it was part of the discussion this shows where it ends up
     $form_state['storage']['results'] = $output ;
     return  ;
}
goofus’s picture

Hi,
Often, an "Add New" form or link is displayed above or below a list report. Is that what you are trying to do? All you do is append lorinpda's listing so that the last line looks something like:
return theme_table($header, $rows).'<br/>'.drupal_get_form("YOUR_FORM_ID");

quiet’s picture

Hi...

no... what I wanted was to show the form (for search selections) then on submit display the search results without redirecting. I figured that is what the _submit hook should be for. ;)

Anyway, I'm happy with it and have made significant progress past that point, including result pagination with pager_query and theme(pager). Go me! lol (what a newbie...sheesh... lol)

allexx’s picture

quiet, thank you for your code.

I just think that here is a little mistake:
It is:
if (empty($form_state['storage']['values'])) {

It must be:
if (empty($form_state['storage']['results'])) {

quiquee’s picture

I am completely stuck with this. I expect to be able to build and display a page within my _submit callback.
My code is similar to yours, but still I dont get any output where I expect to get it

Any help please?

function nounousearch_submit(&$form, &$form_state) {

if (empty($form_state['storage']['values']['canton'] )) {
// if there is no previous values redraw for second step
$nounoustage = "First stage" ;
$form_state['storage']['values'] = $form_state['values'];
// Trying several things here , it doesnt make a difference
// $form_state['rebuild'] = true;

} else {
$nounoustage = "Second stage" ;
// Form is on the second step, process the data here…
$form_state['storage']['values'] = $form_state['values'];
$nounoutype = $form_state['storage']['values'][‘nounoutype’];
$canton = $form_state['storage']['values'][‘canton’];
$commune =$form_state['storage']['values'][‘commune’];

$output = nounou_showresults( $type, $canton, $commune ) ;

// >>>> Doing the same as "quit" in http://drupal.org/comment/reply/542646/3149380#comment-3149380
// >>>> But nothing is displayed
$form_state['storage']['results'] = $output ;
}

drupal_set_message(t($nounoustage));
// This shows the results the way I want "before" the page is built, outside of the template
// just to confirm that $output contains what I want
print $output ;
return ;

}

Jaypan’s picture

Submit functions do not provide a means for display of data. You can return data, but it will not be printed to the screen. If you want to print data from your submit function to the screen, store it in $form_state['storage'], set the form to be rebuilt, and then print it in your form definition.

pupp’s picture

How is this accomplished without a db transaction? I can't seem to be able to pass $form_state into any other function.

nevets’s picture

Since your form function is 'engineers_formfields', you should use 'engineers_formfields_submit' for the name of the submit function.

sriniko’s picture

Hey am trying something similar and used the example given by you but the results would simply not load. Not sure why ? looks like I might be missing something simple here.
Please let me know if your example worked for the search?
Thanks
Srinidhi