Drupal and hook_form_alter()

I’ve been working with Drupal a lot in the last few months, and enjoying the hell out of it. Every day I’m learning some new tidbit, some interesting new scheme that at first seems confusing, but them usually makes me go, “Wow, that’s brilliant!”

I’ve been working with Drupal a lot in the last few months, and enjoying the hell out of it. Every day I’m learning some new tidbit, some interesting new scheme that at first seems confusing, but them usually makes me go, “Wow, that’s brilliant!”

Forms, for instance. Drupal offers a nice API to build and process forms; hook_form_alter() lets your modules modify forms defined in other modules, by adding fields, removing fields, even changing the back-end logic. At first I thought all this hook could do was fields, and I looked for something like hook_form_validate_alter(). But no, the real solution is even more elegant:

mymodule_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'form_whatever') {
    $form['#validate'][] = 'mymodule_form_validation';
  }
}

The $form['#validate'] looks like it contains an array of functions to be called when validating the form (likewise for $form['#submit'], I think). Simple and beautiful. The best part is, nothing is overwritten. Any module may alter any given form, and all their functions will be run. (The order in which they’re run can also be set: turns out modules have weight). I’ve thought for a while that Drupal seems ridiculously over-engineered, but that’s its strength: it allows developers to try out all sorts of crazy schemes like this. The more I learn about Drupal, the more I respect it.