views:

671

answers:

2

I have a simple form with a select menu on the node display page. Is there an easy way to validate the form in my callback function? By validation I don't mean anything advanced, just to check that the values actually existed in the form array. For example, without ajax, if my select menu has 3 items and I add a 4th item and try to submit the form, drupal will give an error saying something similar to "an illegal choice was made, please contact the admin."

With ajax this 4th item you created would get saved into the database. So do I have to write validation like

if ($select_item > 0 && $select_item <= 3) {
  //insert into db
}

Or is there an easier way that will check that the item actually existed in the form array? I'm hoping there is since without ajax, drupal will not submit the form if it was manipulated. Thanks.

EDIT: So I basically need this in my callback function?

$form_state = array('storage' => NULL, 'submitted' => FALSE);
$form_build_id = $_POST['form_build_id'];
$form = form_get_cache($form_build_id, $form_state);
$args = $form['#parameters'];
$form_id = array_shift($args);
$form_state['post'] = $form['#post'] = $_POST;
$form['#programmed'] = $form['#redirect'] = FALSE;
drupal_process_form($form_id, $form, $form_state);

To get $_POST['form_build_id'], I sent it as a data param, is that right? Where I use form_get_cache, looks like there is no data. Kind of lost now.

A: 

Since you're already using AJAX, why not just write a bit of jQuery to only allow form submission if the choice is within the list of legal choices? This can be done within the custom module it already looks like you're working on (using drupal_add_js()).

Mike Crittenden
Well, if the user can manipulate the select menu, they could also manipulate the javascript, that's why I want to do it server side. So do I need to write out all the basic validation checks myself or is there a drupal function for that? Since without ajax they are able to automatically find out of the form was manipulated.
Wade
A: 

It is not especially 'easy', but the standard way to do it would be to use Drupals Forms API for the callback submission as well - that way, you'll get the same validation that would happen on a non js submit.

Take a look at Adding dynamic form elements using AHAH. While it does not match your scenario exactly (they rebuild the form on the callback to add new elements, not to save data), the explanation of the processing workflow is pretty helpful.

Then there are several modules that try to offer AJAX form submission in a generic way - you could check their code on how to do it (or maybe just use them ;)

Finally, there are efforts to put better support this functionality into core in Drupal 7 - the related discussions might also help.

Henrik Opel
Added comment to my original post, didn't know how to add the code in the comments...
Wade