Drupal/Modules/Code Help

From ThinkyWiki

Jump to: navigation, search

Contents

Module Tricks for Common Tasks

Whenever I start a Drupal site I always create a custom module for making smaller tweaks to site behaviors. If a feature requires more than 1 or 2 hooks to implement, I'll make a separate module.

Modules can do so many things...

  • Provide pages and blocks
  • Implement forms
  • Customize forms provided by other modules
  • Add and enforce new permissions
  • Invoke functions from Drupal paths, with arguments
  • Add Javascript and CSS to pages (so can themes)
  • Extend users
  • Modify SQL queries (e.g., to add extra conditions)

...but there are some things you'll do often in modules. This is a set of code samples for common tasks modules often need to do.

Page Callback Tricks

Make a page callback returning raw content

Sometimes it's useful to have a URL that returns something as-is, without any page template. For example, you might want to grab a piece of content using AJAX and insert into the page.

function mymodule_menu() {
  $items['downloadlink/%'] = array(
    'title' => 'Download With Token',
    'page callback' => '_mymodule_filecontent',
    'type' => MENU_CALLBACK,
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
  );
  return $items;
}

function _mymodule_filecontent($arg1=null) {
  // print content instead of returning it
  print _mymodule_get_file_contents($arg1);
  // ...and bypass the theming layer
  exit;
}

Make a page callback returning JSON

Here the same idea applies, but the output is converted to JSON using drupal_to_js. Any flat variable, like an HTML string, would be returned as JSON plaintext. PHP arrays and objects become JSON arrays and objects. To make a textfield autocomplete with user names, just set its #autocomplete_path property to user/autocomplete. This makes it call the function user_autocomplete which returns a JSON dictionary (aka keyed array, aka object). Drupal's autocomplete field code uses the object to build a drop-down menu.

function user_autocomplete($string = '') {
  $matches = array();
  if ($string) {
    $result = db_query_range("SELECT name FROM {users} WHERE LOWER(name) LIKE LOWER('%s%%')", $string, 0, 10);
    while ($user = db_fetch_object($result)) {
      $matches[$user->name] = check_plain($user->name);
    }
  }
  print drupal_to_js($matches);
  exit;
}

Form API Tricks

Hide a field

Collapse a fieldset

Override a checkbox

Personal tools