modules

18 Oct

These Are A Few of My Favorite Things - Drupal 7 Hooks Part 2

in drupal, drupal 6, drupal 7, hooks, modules, planet-drupal

In part 1 of this series of articles about my favorite new Drupal 7 hooks, we looked at the incredibly useful hook_page_alter(). I also stated that in this article I would write about another awesome new pair of hooks:  hook_query_alter() and hook_query_TAG_alter().

If you read my previous article: Drupal 6 vs Drupal 7 Database Primer - Part 1 then you know that in D7 we can build structured queries, also known as dynamic queries. Essentially, we're just creating a query object and by calling certain methods of that query object Drupal generates a SQL statement and executes it. Pretty straightforward, but here's an example as a quick refresher:

<?php
$query = db_select('users', 'u');

$query
  ->condition('u.uid', 0, '<>')
  ->fields('u', array('uid', 'name', 'status', 'created', 'access'))
  ->range(0, 50);

$result = $query->execute();
?>

There's an additional method we can call on this query object:

<?php
$query->addTag('mymodule');
?>

11 Oct

These Are A Few of My Favorite Things - Drupal 7 Hooks Part 1

in drupal, drupal 6, drupal 7, hooks, modules, planet-drupal

I still remember the first "Aha!" moment I had as a new Drupal developer. I had a node form that needed something or another changed on it, and I remember beating my head against template.php for hours until I finally broke down realized I may need to write a custom module to facilitate this change. At the time (which was like eight years ago), I was very much the Drupal n00b, and my experience with writing custom modules was very limited and relegated mostly to writing custom admin forms and the like. After what seemed like hours of scouring through API documentation and forum posts I saw that what I needed to do was implement something everyone was calling: hook_form_alter().

Eight years later and probably hundreds of thousands of lines of code later, I can't imagine my life as a Drupal developer without hooks. Hooks allow us to, well, "hook" into various parts of Drupal and override, change, or add to its behavior. I won't delve into exactly how hooks work, as that's another article, but suffice to say they make my life a lot simpler.

The move from D5 to D6 did not give us many more new hooks to work, but many existing hooks were improved upon. The advent of $form_state is one major improvement that comes to mind immediately. Well, in D7 hooks have gotten the love they deserve. Yes, there are a lot more hooks now, and yes, that means a larger core, but that also means more flexibility for module developers.