Topic “Context”

Roll your own context conditions

The context module provides great flexibility in terms of the available ways to set a context, but it's also remarkably straightforward to define custom conditions.

In order to set arbitrary contexts, hook_context_conditions() is implemented to define values and such. This example will use the value of a CCK field, called field_foo:

/**
 * Implementation of hook_context_conditions().
 */
function mymodule_context_conditions() {
  $items = array();
  // The key used here will be used below when setting the context.
  $items['mymodule_foo'] = array(
    '#title' => t('Field Foo Value'),
    '#description' => t('Set this when field_foo has a certain value.'),
    '#options' => array(
      // Note, these are hardcoded here for simplicity, but could
      // easily use something like CCK's content_allowed_values() api
      // function for more dynamic population.
      'value1' => t('Label 1'),
      'value2' => t('Label 2'),
    ),
    '#type' => 'checkboxes',
  );
  return $items;
}

The only other step is to actually fire the code that sets the context somewhere. In the example of setting a context based on the value of a CCK field, this can be done in hook_nodeapi(). But something like hook_init() can also be used.

function mymodule_nodeapi(&$node, $op, $teaser, $page) {
  if (isset($node->field_foo[0]['value']) &&  $op == 'view' && $page && menu_get_object() === $node) {
    // Use the same key here as used to define the context condition
    // above.  Note, this logic would need some re-working if
    // field_foo allowed multiple values.
    context_set_by_condition('mymodule_foo', check_plain($node->field_foo[0]['value']));
  }
}

That's it. Contexts can now be added through the UI or through code that react to the value of field_foo.

Tagged as: Context, Drupal, Drupal 6

Syndicate content