views_handler_field_chado_count.inc 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /**
  3. * Purpose: Provide a field that counts the number of records in the current table
  4. * are connected to the base table. For example, this field could be used to count
  5. * the number of features connected to a given organism -base table=organism,
  6. * current table=feature: for each record in the organism view count feature records where
  7. * feature.organism_id=organism_id of current organism record
  8. *
  9. * @ingroup views_field_handlers
  10. * @ingroup tripal_core
  11. */
  12. class views_handler_field_chado_count extends views_handler_field {
  13. function init(&$view, $options) {
  14. parent::init($view, $options);
  15. // the table to query is required
  16. // check that it was provided in the field definition and if not warn
  17. if ($this->definition['table_to_query']) {
  18. $this->aliases['current_table'] = $this->definition['table_to_query'];
  19. } else {
  20. drupal_set_message("The field definition ( in hook_views_data() ) needs to specify the 'table_to_query' in order for this fields to work. Field:".$this->field." in the ".$this->table." table definition", 'error');
  21. }
  22. // set aliases
  23. $this->aliases['primary_id'] = $this->table . '_id';
  24. $this->aliases['foreign_key'] = $this->table . '_id';
  25. }
  26. //Needed to ensure that the name of this field is not added to the query
  27. function query() {
  28. $this->add_additional_fields();
  29. }
  30. function pre_render(&$values) {
  31. // Render nothing if the current table wasn't set in the field definition
  32. if(!$this->aliases['current_table']) {
  33. return '';
  34. }
  35. foreach ($values as $key => $record) {
  36. $primary_id = $record->{$this->aliases['primary_id']};
  37. //Select count from database
  38. $sql = 'SELECT count(*) as count FROM %s WHERE %s=%d';
  39. $previous_db = tripal_db_set_active('chado');
  40. $result = db_fetch_object(db_query(
  41. $sql,
  42. $this->aliases['current_table'],
  43. $this->aliases['foreign_key'],
  44. $primary_id
  45. ));
  46. tripal_db_set_active($previous_db);
  47. //Add to view results
  48. $this->view->result[$key]->{$this->field} = $result->count;
  49. }
  50. }
  51. function render($values) {
  52. return $values->{$this->field};
  53. }
  54. }