Views 2 and Drupal - Adding a custom field to the views query

Greg's picture

Here's a quick rundown of how to add a field to Views 2 in Drupal.

It's fairly straightforward, but just in case someone is having difficulty this example should help you along. I'll try my best to explain what is happening.

Let's say for a moment you have some data in a table that pertains to a node. In this example, I'll have an item price in a table called views_price (this table was set up for expressly this purpose) which is keyed on a nid.

So basically we have this:

CREATE TABLE IF NOT EXISTS `views_price` (
  `nid` int(11) NOT NULL,
  `price` float NOT NULL,
  UNIQUE KEY `nid` (`nid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Now, keep in mind that by default Ubercart will store the product price in the table uc_products, so this may be an odd example for some of you. We have some special requirements that necessitate us having this data in a separate table. However, this data could literally be anything pertaining to the node, so replace as necessary.

Now, the next step is adding hook_views_api() to a custom module. We have a 'helper' module full of these sorts of functions, but you could just as well create a new module for this purpose. Here's a look at the function:

function mymodule_views_api() {
  return array(
    'api' => 2,
    'path' => 
   drupal_get_path('module', 'mymodule'),
  );
}

As you would with any hook function, replace any instance of "mymodule" with the name of the module that is implementing this hook. This will apply to all code in this post moving forward.

Here we're telling Views to follow the Views 2 API, and pointing to the directory of "mymodule" as the path to where you will find "mymodule.views.inc". That's where we will be storing the code that will do the heavy lifting. Create that file now and add it to the module directory, ie. "/drupal_base_path/sites/all/modules/mymodule/mymodule.views.inc".

In "mymodule.views.inc" we will implement hook_views_data() which will let Views 2 know that we have some data in our table that we would like to define as a field attached to a node. Here's the layout of how I implemented it and I'll explain below:

function mymodule_views_data() {
  $data['views_price'] = array(
    'table' => array(
      'group' => 'My Custom Data',
      'title' => 'views_price',
      'join' => array(
        'node' => array(
          'left_field' => 'nid',
          'field' => 'nid',        
         ),
      ),
    ),
    'price' => array(
      'title' => t('Price'),
      'help' => t('A product price generated 
            by the mymodule module.'), 
      'field' => array(
        'handler' => 'views_handler_field',
        'click sortable' => TRUE,
      ),
    ),
  );

  return $data;  
}

OK, so what did we do here? First we set up the data array and key it with the name of the table, which in this case is "views_price". It will contain (for this example) two arrays: "table" and price". The "table" array defines the table where we are storing our data, and the "price" array defines the field we are adding.

The group and title in the "table" array are fairly straight forward; they appear as the labels for group and title that you will see in the views admin when adding the field to your view. In our example, we're joining our new table to the node table using nid, so leave the "join" array as it is if you're doing something similar.

The "price" array defines the field we want to add (this should be the name of the field in the database). Title is again straightforward, and 'help' is the text you see below the checkbox for the field in the Views 2 admin.

The "field" key contains an array witch defines the handler for this particular field (in our case we are telling Views we want to use views_handler_field) and also that it should be click sortable when displayed in a table.

Finally we return our $data array, and Views 2 does the rest.

Easy, no?

This is a very rudimentary example of adding a field to Views 2, so please consult the documentation for anything more complicated. As a matter of fact, you should consult the Views documentation regardless.

Here's some links to get you on you way:

http://drupal.org/project/views
http://views-help.doc.logrus.com/
http://views.doc.logrus.com/

Feel free to leave a comment if you have any questions or if you spot an error (or just to say hello).

Perfect

Thank you soooooooooooooooooo much.
ouaaa,
thanks again, works so fine, clear, everything.
I'm from Paris, building a module for OCDE new site.., in drupal since 2 months...!

Great post, thank you very much...

Can't thank you enough as I have been looking for this for longer than I want to admit.

you're welcome

you're welcome

Thanks. It was usefull for

Thanks. It was usefull for me.

gh

I'm thankful to the one who wrote this passage. I always read and write this style of articles. Also, as a daily writer, I present my respects to the all

In my opinion, people should research first and write then.

Regards.

Thanks! (I think)

Thanks! (I think)

CCK?

Hey Greg, Great stuff here, views needs all the help with the How To's as it can. Earl writes great code, but his stuff has disparate documentation to say the least.

Something that struck my curiosity. Why would you choose to do a custom table instead of use CCK for adding the price field?