tags:

views:

195

answers:

2

I am building a custom module that will allow my users to do a simple query against an MS SQL database. I've built the form using hook_form() and have gotten validation to work.

I'm planning on retrieving the data from hook_form_submit(), but once I've done that, how do I append it below the form? It does not appear that I have access to $output from hook_form_submit(). I'm at a loss as to what to do next.

Thanks

Dana

+2  A: 

When you are rendering the form you should check for $form_state['values'] to see if the user has already submitted a form when you're rendering the form. Then you could paint the form results in the same step as painting the form.

The first time the user loads the form page the $form_state variable won't contain any submitted form info so you can render an empty results table.

There's a good illustration of the Drupal Form API workflow on Drupal.org here: Form API Internal Workflow Illustration

alxp
Thanks for this. But the problem is that $form_state isn't available until hook_form_submit() correct? By then it's too late to update the form. I need to get the post values in my callback function (which in my case is sqlquery_page(). I suppose I can just grab $_POST and get my values there.
Dana
The $form_state variable is passed when drupal_get_form is called. See http://api.drupal.org/api/function/example_form/6. As alxp said, you can check for submitted values here, and if they exist, output the content fetched from your external source database.
jhedstrom
A: 

The problem in trying to output data in the hook_form() method is that the method gets invoked twice which clears the post values the second time through. Throw a dpm($form_state) in the hook_form() function and you'll see two sets of post data. One with values and one without.

So after dissecting the built in Search module, which pretty much operates exactly the way I want my form to work, I figured out how this is done. Well, at least one way you can do it.

What Search module does is take the values from $form_state in hook_form_submit() and pastes them into the URL, then it sets the $form_state['redirect'] to that new URL, effectively storing those variables in the URL and changing the POST to a GET.

Now, in the callback, they extract those values from the URL, do the search on them, THEN they call drupal_get_form(), append the results to the end and return it.

There's another solution HERE where they use SESSION to store the values until the second trip through. Weird, but it works.

Dana

related questions