Extensible Tables

Furthermore, tables are now extensible! Whoa!!! Extensible tables. Who would've thought? That's right, your module may define a table that can be extended by other modules using the TAPIr hook_table_alter(). Our product catalog may by default display a picture, a product name, and a price. Someone else may come along and develop an inventory system that makes it possible to show the number of that product available. They just need to know the table ID and can very easily add that column to the table. Here's the anatomy of the implementation of that hook using our same test table from above:

<?php
function tapir_table_alter($table_id, $op) {
  if (
$table_id == 'my_test_table') {
    switch (
$op) {
      case
'fields':
       
$fields[] = array('name' => 'gender', 'title' => t('Gender'), 'weight' => 3,
                         
'enabled' => FALSE);
        return
$fields;

      case

'data':
       
$data['score'] = array('male', 'female');
        return
$data;
    }
  }
}
?>

If this code were included in an enabled module, it would then enable the gender field for that table. In this case, the field wouldn't show by default but could be turned on by the user if he wanted.

Also, please realize that even though the data arrays returned in all the examples were hard coded, this data can be grabbed from the database dynamically like anything else. Our examples very easily could have constructed the arrays like so:

<?php
$result
= db_query("SELECT name, age FROM people WHERE .....");
while (
$row = db_fetch_object($result)) {
 
$data['name'][] = $row->name;
 
$data['age'][] = $row->age;
}
?>