Example 4: Extending a Table

One of the advantages of defining tables with TAPIr is that it gives you a very simply interface for extending tables. Besides making it easy for site owners to configure the look and content of tables, TAPIr makes it extremely easy for developers to create modules that affect tables defined in other modules. Drupal allows this functionality with its hook_form_alter, so similarly TAPIr allows this with its hook_table_alter. For now this function is used to add extra fields to tables.

The example application here supposes a site owner has installed some sort of contact manager into his or her Drupal site that uses TAPIr to define a table of contact information for clients. The original offering included name, phone number, and email address. The owner needed it to display the personal website address of the contacts, so he developed an extremely lightweight module that extended the table.

(Note: This example uses hardcoded data, whereas it is more practical for this data to be loaded dynamically from the database. The next example models this process.)

Example: view page

Code:

<?php
function tapirtest_menu($may_cache) {
  if (
$may_cache) {
   
$items[] = array(
     
'path' => 'tapirtest/example_4',
     
'title' => t('Example 4: Extending a Table'),
     
'callback' => 'tapirtest_example_4',
     
'access' => user_access('access content'),
     
'type' => MENU_CALLBACK,
    );
  }
  return
$items;
}

function

tapirtest_example_4() {
 
$output = '<p>'. tapir_get_table('tapirtest_example_table_4', $null) .'</p>';
  return
$output;
}

function

tapirtest_example_table_4($op) {
  switch (
$op) {
    case
'fields':
     
$fields[] = array('name' => 'name', 'title' => t('Name'), 'weight' => 0, 'enabled' => TRUE);
     
$fields[] = array('name' => 'phone', 'title' => t('Phone #'), 'weight' => 1,
                       
'enabled' => TRUE);
     
$fields[] = array('name' => 'email', 'title' => t('E-mail Address'), 'weight' => 2,
                       
'enabled' => TRUE);
      return
$fields;
    case
'data':
     
$data['name'] = array('Horatio Sans', 'Reginald Pock');
     
$data['phone'] = array('555-555-5555', '555-555-5556');
     
$data['email'] = array('horatio@email.com', 'reginald@email.com');
      return
$data;
  }
}

function

tapirtest_table_alter ($table_id, $op, $args) {
  if (
$table_id == 'tapirtest_example_table_4') {
    switch (
$op) {
      case
'fields':
       
$fields[] = array('name' => 'site', 'title' => t('Website'), 'weight' => 3,
                       
'enabled' => TRUE);
        return
$fields;
      case
'data':
       
$data['site'] = array('www.horatio.name', 'www.reginald.name');
        return
$data;
    }
  }
}
?>