views_handler_field_chado_count.inc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. $result = db_fetch_object(chado_query(
  42. $sql,
  43. $this->aliases['current_table'],
  44. $this->aliases['foreign_key'],
  45. $primary_id
  46. ));
  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. }