EntityReference_SelectionHandler_Views.class.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. <?php
  2. /**
  3. * Entity handler for Views.
  4. */
  5. class EntityReference_SelectionHandler_Views implements EntityReference_SelectionHandler {
  6. /**
  7. * Implements EntityReferenceHandler::getInstance().
  8. */
  9. public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
  10. return new EntityReference_SelectionHandler_Views($field, $instance, $entity);
  11. }
  12. protected function __construct($field, $instance, $entity) {
  13. $this->field = $field;
  14. $this->instance = $instance;
  15. $this->entity = $entity;
  16. }
  17. /**
  18. * Implements EntityReferenceHandler::settingsForm().
  19. */
  20. public static function settingsForm($field, $instance) {
  21. $view_settings = empty($field['settings']['handler_settings']['view']) ? '' : $field['settings']['handler_settings']['view'];
  22. $displays = views_get_applicable_views('entityreference display');
  23. // Filter views that list the entity type we want, and group the separate
  24. // displays by view.
  25. $entity_info = entity_get_info($field['settings']['target_type']);
  26. $options = array();
  27. foreach ($displays as $data) {
  28. list($view, $display_id) = $data;
  29. if ($view->base_table == $entity_info['base table']) {
  30. $options[$view->name . ':' . $display_id] = $view->name . ' - ' . $view->display[$display_id]->display_title;
  31. }
  32. }
  33. // The value of the 'view_and_display' select below will need to be split
  34. // into 'view_name' and 'view_display' in the final submitted values, so
  35. // we massage the data at validate time on the wrapping element (not
  36. // ideal).
  37. $form['view']['#element_validate'] = array('entityreference_view_settings_validate');
  38. if ($options) {
  39. $default = !empty($view_settings['view_name']) ? $view_settings['view_name'] . ':' . $view_settings['display_name'] : NULL;
  40. $form['view']['view_and_display'] = array(
  41. '#type' => 'select',
  42. '#title' => t('View used to select the entities'),
  43. '#required' => TRUE,
  44. '#options' => $options,
  45. '#default_value' => $default,
  46. '#description' => '<p>' . t('Choose the view and display that select the entities that can be referenced.<br />Only views with a display of type "Entity Reference" are eligible.') . '</p>',
  47. );
  48. $default = !empty($view_settings['args']) ? implode(', ', $view_settings['args']) : '';
  49. $description = t('Provide a comma separated list of arguments to pass to the view.') . '<br />' . t('This field supports tokens.');
  50. if (!module_exists('token')) {
  51. $description .= '<br>' . t('Install the <a href="@url">token module</a> to get more tokens and display available once.', array('@url' => 'http://drupal.org/project/token'));
  52. }
  53. $form['view']['args'] = array(
  54. '#type' => 'textfield',
  55. '#title' => t('View arguments'),
  56. '#default_value' => $default,
  57. '#required' => FALSE,
  58. '#description' => $description,
  59. '#maxlength' => '512',
  60. );
  61. if (module_exists('token')) {
  62. // Get the token type for the entity type our field is in (a type 'taxonomy_term' has a 'term' type token).
  63. $info = entity_get_info($instance['entity_type']);
  64. $form['view']['tokens'] = array(
  65. '#theme' => 'token_tree',
  66. '#token_types' => array($info['token type']),
  67. '#global_types' => TRUE,
  68. '#click_insert' => TRUE,
  69. '#dialog' => TRUE,
  70. );
  71. }
  72. }
  73. else {
  74. $form['view']['no_view_help'] = array(
  75. '#markup' => '<p>' . t('No eligible views were found. <a href="@create">Create a view</a> with an <em>Entity Reference</em> display, or add such a display to an <a href="@existing">existing view</a>.', array(
  76. '@create' => url('admin/structure/views/add'),
  77. '@existing' => url('admin/structure/views'),
  78. )) . '</p>',
  79. );
  80. }
  81. return $form;
  82. }
  83. protected function initializeView($match = NULL, $match_operator = 'CONTAINS', $limit = 0, $ids = NULL) {
  84. $view_name = $this->field['settings']['handler_settings']['view']['view_name'];
  85. $display_name = $this->field['settings']['handler_settings']['view']['display_name'];
  86. $args = $this->field['settings']['handler_settings']['view']['args'];
  87. $entity_type = $this->field['settings']['target_type'];
  88. // Check that the view is valid and the display still exists.
  89. $this->view = views_get_view($view_name);
  90. if (!$this->view || !isset($this->view->display[$display_name]) || !$this->view->access($display_name)) {
  91. watchdog('entityreference', 'The view %view_name is no longer eligible for the %field_name field.', array('%view_name' => $view_name, '%field_name' => $this->instance['label']), WATCHDOG_WARNING);
  92. return FALSE;
  93. }
  94. $this->view->set_display($display_name);
  95. $this->view->pre_execute();
  96. // Make sure the query is not cached.
  97. $this->view->is_cacheable = FALSE;
  98. // Pass options to the display handler to make them available later.
  99. $entityreference_options = array(
  100. 'match' => $match,
  101. 'match_operator' => $match_operator,
  102. 'limit' => $limit,
  103. 'ids' => $ids,
  104. );
  105. $this->view->display_handler->set_option('entityreference_options', $entityreference_options);
  106. return TRUE;
  107. }
  108. /**
  109. * Implements EntityReferenceHandler::getReferencableEntities().
  110. */
  111. public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
  112. $display_name = $this->field['settings']['handler_settings']['view']['display_name'];
  113. $args = $this->handleArgs($this->field['settings']['handler_settings']['view']['args']);
  114. $result = array();
  115. if ($this->initializeView($match, $match_operator, $limit)) {
  116. // Get the results.
  117. $result = $this->view->execute_display($display_name, $args);
  118. }
  119. $return = array();
  120. if ($result) {
  121. $target_type = $this->field['settings']['target_type'];
  122. $entities = entity_load($target_type, array_keys($result));
  123. foreach($entities as $entity) {
  124. list($id,, $bundle) = entity_extract_ids($target_type, $entity);
  125. $return[$bundle][$id] = $result[$id];
  126. }
  127. }
  128. return $return;
  129. }
  130. /**
  131. * Implements EntityReferenceHandler::countReferencableEntities().
  132. */
  133. function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
  134. $this->getReferencableEntities($match, $match_operator);
  135. return $this->view->total_items;
  136. }
  137. function validateReferencableEntities(array $ids) {
  138. $display_name = $this->field['settings']['handler_settings']['view']['display_name'];
  139. $args = $this->handleArgs($this->field['settings']['handler_settings']['view']['args']);
  140. $result = array();
  141. if ($this->initializeView(NULL, 'CONTAINS', 0, $ids)) {
  142. // Get the results.
  143. $entities = $this->view->execute_display($display_name, $args);
  144. if (!empty($entities)) {
  145. $result = array_keys($entities);
  146. }
  147. }
  148. return $result;
  149. }
  150. /**
  151. * Implements EntityReferenceHandler::validateAutocompleteInput().
  152. */
  153. public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
  154. return NULL;
  155. }
  156. /**
  157. * Implements EntityReferenceHandler::getLabel().
  158. */
  159. public function getLabel($entity) {
  160. return entity_label($this->field['settings']['target_type'], $entity);
  161. }
  162. /**
  163. * Implements EntityReferenceHandler::entityFieldQueryAlter().
  164. */
  165. public function entityFieldQueryAlter(SelectQueryInterface $query) {
  166. }
  167. /**
  168. * Handles arguments for views.
  169. *
  170. * Replaces tokens using token_replace().
  171. *
  172. * @param array $args
  173. * Usually $this->field['settings']['handler_settings']['view']['args'].
  174. *
  175. * @return array
  176. * The arguments to be send to the View.
  177. */
  178. protected function handleArgs($args) {
  179. if (!module_exists('token')) {
  180. return $args;
  181. }
  182. // Parameters for token_replace().
  183. $data = array();
  184. $options = array('clear' => TRUE);
  185. if ($entity = $this->entity) {
  186. // D7 HACK: For new entities, entity and revision id are not set. This leads to
  187. // * token replacement emitting PHP warnings
  188. // * views choking on empty arguments
  189. // We workaround this by filling in '0' for these IDs
  190. // and use a clone to leave no traces of our unholy doings.
  191. $info = entity_get_info($this->instance['entity_type']);
  192. if (!isset($entity->{$info['entity keys']['id']})) {
  193. $entity = clone $entity;
  194. $entity->{$info['entity keys']['id']} = '0';
  195. if (!empty($info['entity keys']['revision'])) {
  196. $entity->{$info['entity keys']['revision']} = '0';
  197. }
  198. }
  199. $data[$info['token type']] = $entity;
  200. }
  201. // Replace tokens for each argument.
  202. foreach ($args as $key => $arg) {
  203. $args[$key] = token_replace($arg, $data, $options);
  204. }
  205. return $args;
  206. }
  207. }
  208. function entityreference_view_settings_validate($element, &$form_state, $form) {
  209. // Split view name and display name from the 'view_and_display' value.
  210. if (!empty($element['view_and_display']['#value'])) {
  211. list($view, $display) = explode(':', $element['view_and_display']['#value']);
  212. }
  213. else {
  214. form_error($element, t('The views entity selection mode requires a view.'));
  215. return;
  216. }
  217. // Explode the 'args' string into an actual array. Beware, explode() turns an
  218. // empty string into an array with one empty string. We'll need an empty array
  219. // instead.
  220. $args_string = trim($element['args']['#value']);
  221. if ($args_string === '') {
  222. $args = array();
  223. }
  224. else {
  225. // array_map is called to trim whitespaces from the arguments.
  226. $args = array_map('trim', explode(',', $args_string));
  227. }
  228. $value = array('view_name' => $view, 'display_name' => $display, 'args' => $args);
  229. form_set_value($element, $value, $form_state);
  230. }