Monday, April 14, 2014

How to work with confirm_form in Drupal 7

Screen capture of the confirmation screen.
Either my google-fu is losing its kung-fu grip or no one has really good documentation on confirm_form. This post hopes to change that (on both respects, since I hope to be able to find my own post later ;)). I have someone who's writing some custom Drupal module code to delete an object, but we want to confirm it with the user before actually deleting the object and she's running into a wall trying to understand how to accomplish that.

The trick is to use $form_state['rebuild'] = TRUE in your submit function. This kicks it back to your form method. So the form method should have two branches, one if it's the initial request and one if it's the confirmation request. Then your submit method should also have two branches, one for the initial submission and one for the confirmation submission. You should also use $form_state['storage'] to store the underlying states and data required for state discernment and form completion. Here's a simplified gist of what I'm getting at:

The healthy dose of dpm()'s are useful to help figure out what's going on, too. If you don't know, dpm() is a great function that's provided by the devel module.

I also uploaded the example module on GitHub for your perusal, download and adoption. :)