views_handler_field_chado_count.inc 2.2 KB

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