schema api

Having fun with Schema API

Everyone who works with Drupal probably knows CCK. For several reasons - which I'm not going to explain here - we decided to ditch CCK for a project we are currenly working on and write a custom module that adds field to a node type. We need a couple of node types, but instead of using CCK to add new fields, we use the Schema API to define database tables and fields. Besides the known keys from the API, we defined a couple of our own which we use to build node forms. A quick example:

<?php
function hook_schema() {
 
$schema['example'] = array(
   
'fields' => array(
     
'example_field' => array(
       
'type' => 'varchar',
       
'description' => 'Example description',
       
'not null' => TRUE, // Used to set #required or not
       
'#title' => 'Example title',
       
'#widget' => 'textfield',
       
'#widget_validate' => 'validation function',
       
// Other keys like #widget_options, #widget_save etc ...
     
), 
    ),
   
// ...
 
);

  return

$schema;
}
?>

When a node edit form is displayed and we can confirm the node type supports our form functions (with a simple hook), the schema is analyzed and it will render a textfield. All default FAPI elements in Drupal are supported of course and if we need something else, we can either use hook_elements to expose new form element types or install other API's out there which expose useful form elements (eg Date API). CRUD operations and loading data into the node object is handled by our code, so we are now able to easily create multiple node types with extra fields thanks to the extra keys we define in the install files. Basic support for multiple values (only one table!) and exposing fields to views is already done too, so we have a pretty solid API to play with.

Right now, we aren't sure if we're going public with the code because:

  • Only D6 is interesting since D5 core doesn't come with Schema API and D7 now has fields in core.
  • CCK is the de-facto standard for creating new node types with extra fields
  • CCK is more supported and widely used
  • our tool is really more of a developers tool

What I really wanted to tell with this post is that Drupal comes with a strong API and that with a bit of imagination you are able to achieve really cool things. If you want some more details, feel free to bug me at the next DrupalCon in DC, I'd be happy to show you some code and a quick demo.

Topics 

drupal, schema api, planet
Subscribe to RSS - schema api

You are here