Drupal 7's new database and how to use computed field for the basics!

Drupal 7's new database and how to use computed field for the basics!

Quick Explanation:

One of the major changes from Drupal 6 to Drupal 7 is the database and how it is structured. In Drupal 6, each content type was its own table. Not the case in Drupal 7. In Drupal 7, each field is its own table and the field’s content type is only a column in the field’s table. I found this while trying to write custom queries in Computed Field. I briefly struggled with how I was going to write relational queries if content types are no longer tables, and each field is its own table … until I discovered entity type and entity ID. I had read and heard about them but didn’t quite grasp the difference until now. Each node created in Drupal 7 has its own entity ID. That entity ID is consistent across all your tables (which are fields). Therefore, to compare things, simply set their entity_id equal to one another.

 

Computed Field Example:

I struggled with new Drupal to write a simple Computed Field to do basic arithmetic. So I figured I would post in case someone needs examples.

 

Computed Code:

$entity_field[0]['value'] =

  array_pop(array_pop(field_get_items($entity_type, $entity, 'field_current_budget_balance'))) -

  array_pop(array_pop(field_get_items($entity_type, $entity, 'field_future_planned_expenses')));

 

Display Code:

$display_output = $entity_field_item['value'];

 

Al this does is fetch the field called “field_current_budget_balance” and subtract from it the value of field “field_future_planned_expenses”.

The next example I wanted to run queries on the Drupal database. Again, easy with Computed Field:

 

Computed Code:

$entity_field[0]['value'] = db_query("

SELECT SUM( field_cost_budget_value )

FROM field_data_field_cost_budget, field_data_field_award_number_s, field_data_field_project_number_s

WHERE field_award_number_s_value = 'IP00157'

AND field_project_number_s_value =106842

AND field_data_field_cost_budget.entity_id = field_data_field_award_number_s.entity_id

AND field_data_field_cost_budget.entity_id = field_data_field_project_number_s.entity_id

")->fetchField();

 

Display Code:

$display_output = $entity_field_item['value'];

 

Don’t forget ->fetchField();

about the author

David Leary

related posts