PageRenderTime 73ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/core/modules/views/src/Plugin/views/exposed_form/ExposedFormPluginBase.php

https://gitlab.com/reasonat/test8
PHP | 379 lines | 253 code | 47 blank | 79 comment | 42 complexity | 7772d0124a26b268572347502e95e568 MD5 | raw file
  1. <?php
  2. namespace Drupal\views\Plugin\views\exposed_form;
  3. use Drupal\Component\Utility\Html;
  4. use Drupal\Core\Cache\Cache;
  5. use Drupal\Core\Cache\CacheableDependencyInterface;
  6. use Drupal\Core\Form\FormState;
  7. use Drupal\Core\Form\FormStateInterface;
  8. use Drupal\views\Plugin\views\PluginBase;
  9. /**
  10. * @defgroup views_exposed_form_plugins Views exposed form plugins
  11. * @{
  12. * Plugins that handle validation, submission, and rendering of exposed forms.
  13. *
  14. * Exposed forms are used for filters, sorts, and pager settings that are
  15. * exposed to site visitors. Exposed form plugins handle the rendering,
  16. * validation, and submission of exposed forms, and may add additional form
  17. * elements.
  18. *
  19. * Exposed form plugins extend
  20. * \Drupal\views\Plugin\views\exposed_form\ExposedFormPluginBase. They must be
  21. * annotated with \Drupal\views\Annotation\ViewsExposedForm annotation,
  22. * and they must be in namespace directory Plugin\views\exposed_form.
  23. */
  24. /**
  25. * Base class for Views exposed filter form plugins.
  26. */
  27. abstract class ExposedFormPluginBase extends PluginBase implements CacheableDependencyInterface {
  28. /**
  29. * {@inheritdoc}
  30. */
  31. protected $usesOptions = TRUE;
  32. protected function defineOptions() {
  33. $options = parent::defineOptions();
  34. $options['submit_button'] = array('default' => $this->t('Apply'));
  35. $options['reset_button'] = array('default' => FALSE);
  36. $options['reset_button_label'] = array('default' => $this->t('Reset'));
  37. $options['exposed_sorts_label'] = array('default' => $this->t('Sort by'));
  38. $options['expose_sort_order'] = array('default' => TRUE);
  39. $options['sort_asc_label'] = array('default' => $this->t('Asc'));
  40. $options['sort_desc_label'] = array('default' => $this->t('Desc'));
  41. return $options;
  42. }
  43. public function buildOptionsForm(&$form, FormStateInterface $form_state) {
  44. parent::buildOptionsForm($form, $form_state);
  45. $form['submit_button'] = array(
  46. '#type' => 'textfield',
  47. '#title' => $this->t('Submit button text'),
  48. '#default_value' => $this->options['submit_button'],
  49. '#required' => TRUE,
  50. );
  51. $form['reset_button'] = array(
  52. '#type' => 'checkbox',
  53. '#title' => $this->t('Include reset button (resets all applied exposed filters)'),
  54. '#default_value' => $this->options['reset_button'],
  55. );
  56. $form['reset_button_label'] = array(
  57. '#type' => 'textfield',
  58. '#title' => $this->t('Reset button label'),
  59. '#description' => $this->t('Text to display in the reset button of the exposed form.'),
  60. '#default_value' => $this->options['reset_button_label'],
  61. '#required' => TRUE,
  62. '#states' => array(
  63. 'invisible' => array(
  64. 'input[name="exposed_form_options[reset_button]"]' => array('checked' => FALSE),
  65. ),
  66. ),
  67. );
  68. $form['exposed_sorts_label'] = array(
  69. '#type' => 'textfield',
  70. '#title' => $this->t('Exposed sorts label'),
  71. '#default_value' => $this->options['exposed_sorts_label'],
  72. '#required' => TRUE,
  73. );
  74. $form['expose_sort_order'] = array(
  75. '#type' => 'checkbox',
  76. '#title' => $this->t('Allow people to choose the sort order'),
  77. '#description' => $this->t('If sort order is not exposed, the sort criteria settings for each sort will determine its order.'),
  78. '#default_value' => $this->options['expose_sort_order'],
  79. );
  80. $form['sort_asc_label'] = array(
  81. '#type' => 'textfield',
  82. '#title' => $this->t('Label for ascending sort'),
  83. '#default_value' => $this->options['sort_asc_label'],
  84. '#required' => TRUE,
  85. '#states' => array(
  86. 'visible' => array(
  87. 'input[name="exposed_form_options[expose_sort_order]"]' => array('checked' => TRUE),
  88. ),
  89. ),
  90. );
  91. $form['sort_desc_label'] = array(
  92. '#type' => 'textfield',
  93. '#title' => $this->t('Label for descending sort'),
  94. '#default_value' => $this->options['sort_desc_label'],
  95. '#required' => TRUE,
  96. '#states' => array(
  97. 'visible' => array(
  98. 'input[name="exposed_form_options[expose_sort_order]"]' => array('checked' => TRUE),
  99. ),
  100. ),
  101. );
  102. }
  103. /**
  104. * Render the exposed filter form.
  105. *
  106. * This actually does more than that; because it's using FAPI, the form will
  107. * also assign data to the appropriate handlers for use in building the
  108. * query.
  109. */
  110. public function renderExposedForm($block = FALSE) {
  111. // Deal with any exposed filters we may have, before building.
  112. $form_state = (new FormState())
  113. ->setStorage([
  114. 'view' => $this->view,
  115. 'display' => &$this->view->display_handler->display,
  116. 'rerender' => TRUE,
  117. ])
  118. ->setMethod('get')
  119. ->setAlwaysProcess()
  120. ->disableRedirect();
  121. // Some types of displays (eg. attachments) may wish to use the exposed
  122. // filters of their parent displays instead of showing an additional
  123. // exposed filter form for the attachment as well as that for the parent.
  124. if (!$this->view->display_handler->displaysExposed() || (!$block && $this->view->display_handler->getOption('exposed_block'))) {
  125. $form_state->set('rerender', NULL);
  126. }
  127. if (!empty($this->ajax)) {
  128. $form_state->set('ajax', TRUE);
  129. }
  130. $form = \Drupal::formBuilder()->buildForm('\Drupal\views\Form\ViewsExposedForm', $form_state);
  131. if (!$this->view->display_handler->displaysExposed() || (!$block && $this->view->display_handler->getOption('exposed_block'))) {
  132. return array();
  133. }
  134. else {
  135. return $form;
  136. }
  137. }
  138. public function query() {
  139. $view = $this->view;
  140. $exposed_data = isset($view->exposed_data) ? $view->exposed_data : array();
  141. $sort_by = isset($exposed_data['sort_by']) ? $exposed_data['sort_by'] : NULL;
  142. if (!empty($sort_by)) {
  143. // Make sure the original order of sorts is preserved
  144. // (e.g. a sticky sort is often first)
  145. if (isset($view->sort[$sort_by])) {
  146. $view->query->orderby = array();
  147. foreach ($view->sort as $key => $sort) {
  148. if (!$sort->isExposed()) {
  149. $sort->query();
  150. }
  151. elseif ($key == $sort_by) {
  152. if (isset($exposed_data['sort_order']) && in_array($exposed_data['sort_order'], array('ASC', 'DESC'))) {
  153. $sort->options['order'] = $exposed_data['sort_order'];
  154. }
  155. $sort->setRelationship();
  156. $sort->query();
  157. }
  158. }
  159. }
  160. }
  161. }
  162. public function preRender($values) { }
  163. public function postRender(&$output) { }
  164. public function preExecute() { }
  165. public function postExecute() { }
  166. /**
  167. * Alters the view exposed form.
  168. *
  169. * @param $form
  170. * The form build array. Passed by reference.
  171. * @param $form_state
  172. * The form state. Passed by reference.
  173. */
  174. public function exposedFormAlter(&$form, FormStateInterface $form_state) {
  175. if (!empty($this->options['submit_button'])) {
  176. $form['actions']['submit']['#value'] = $this->options['submit_button'];
  177. }
  178. // Check if there is exposed sorts for this view
  179. $exposed_sorts = array();
  180. foreach ($this->view->sort as $id => $handler) {
  181. if ($handler->canExpose() && $handler->isExposed()) {
  182. $exposed_sorts[$id] = Html::escape($handler->options['expose']['label']);
  183. }
  184. }
  185. if (count($exposed_sorts)) {
  186. $form['sort_by'] = array(
  187. '#type' => 'select',
  188. '#options' => $exposed_sorts,
  189. '#title' => $this->options['exposed_sorts_label'],
  190. );
  191. $sort_order = array(
  192. 'ASC' => $this->options['sort_asc_label'],
  193. 'DESC' => $this->options['sort_desc_label'],
  194. );
  195. $user_input = $form_state->getUserInput();
  196. if (isset($user_input['sort_by']) && isset($this->view->sort[$user_input['sort_by']])) {
  197. $default_sort_order = $this->view->sort[$user_input['sort_by']]->options['order'];
  198. }
  199. else {
  200. $first_sort = reset($this->view->sort);
  201. $default_sort_order = $first_sort->options['order'];
  202. }
  203. if (!isset($user_input['sort_by'])) {
  204. $keys = array_keys($exposed_sorts);
  205. $user_input['sort_by'] = array_shift($keys);
  206. $form_state->setUserInput($user_input);
  207. }
  208. if ($this->options['expose_sort_order']) {
  209. $form['sort_order'] = array(
  210. '#type' => 'select',
  211. '#options' => $sort_order,
  212. '#title' => $this->t('Order', array(), array('context' => 'Sort order')),
  213. '#default_value' => $default_sort_order,
  214. );
  215. }
  216. $form['submit']['#weight'] = 10;
  217. }
  218. if (!empty($this->options['reset_button'])) {
  219. $form['actions']['reset'] = array(
  220. '#value' => $this->options['reset_button_label'],
  221. '#type' => 'submit',
  222. '#weight' => 10,
  223. );
  224. // Get an array of exposed filters, keyed by identifier option.
  225. $exposed_filters = [];
  226. foreach ($this->view->filter as $id => $handler) {
  227. if ($handler->canExpose() && $handler->isExposed() && !empty($handler->options['expose']['identifier'])) {
  228. $exposed_filters[$handler->options['expose']['identifier']] = $id;
  229. }
  230. }
  231. $all_exposed = array_merge($exposed_sorts, $exposed_filters);
  232. // Set the access to FALSE if there is no exposed input.
  233. if (!array_intersect_key($all_exposed, $this->view->getExposedInput())) {
  234. $form['actions']['reset']['#access'] = FALSE;
  235. }
  236. }
  237. $pager = $this->view->display_handler->getPlugin('pager');
  238. if ($pager) {
  239. $pager->exposedFormAlter($form, $form_state);
  240. $form_state->set('pager_plugin', $pager);
  241. }
  242. }
  243. public function exposedFormValidate(&$form, FormStateInterface $form_state) {
  244. if ($pager_plugin = $form_state->get('pager_plugin')) {
  245. $pager_plugin->exposedFormValidate($form, $form_state);
  246. }
  247. }
  248. /**
  249. * This function is executed when exposed form is submitted.
  250. *
  251. * @param $form
  252. * Nested array of form elements that comprise the form.
  253. * @param $form_state
  254. * The current state of the form.
  255. * @param $exclude
  256. * Nested array of keys to exclude of insert into
  257. * $view->exposed_raw_input
  258. */
  259. public function exposedFormSubmit(&$form, FormStateInterface $form_state, &$exclude) {
  260. if (!$form_state->isValueEmpty('op') && $form_state->getValue('op') == $this->options['reset_button_label']) {
  261. $this->resetForm($form, $form_state);
  262. }
  263. if ($pager_plugin = $form_state->get('pager_plugin')) {
  264. $pager_plugin->exposedFormSubmit($form, $form_state, $exclude);
  265. $exclude[] = 'pager_plugin';
  266. }
  267. }
  268. public function resetForm(&$form, FormStateInterface $form_state) {
  269. // _SESSION is not defined for users who are not logged in.
  270. // If filters are not overridden, store the 'remember' settings on the
  271. // default display. If they are, store them on this display. This way,
  272. // multiple displays in the same view can share the same filters and
  273. // remember settings.
  274. $display_id = ($this->view->display_handler->isDefaulted('filters')) ? 'default' : $this->view->current_display;
  275. if (isset($_SESSION['views'][$this->view->storage->id()][$display_id])) {
  276. unset($_SESSION['views'][$this->view->storage->id()][$display_id]);
  277. }
  278. // Set the form to allow redirect.
  279. if (empty($this->view->live_preview) && !\Drupal::request()->isXmlHttpRequest()) {
  280. $form_state->disableRedirect(FALSE);
  281. }
  282. else {
  283. $form_state->setRebuild();
  284. $this->view->exposed_data = array();
  285. }
  286. $form_state->setRedirect('<current>');
  287. $form_state->setValues([]);
  288. }
  289. /**
  290. * {@inheritdoc}
  291. */
  292. public function getCacheMaxAge() {
  293. return Cache::PERMANENT;
  294. }
  295. /**
  296. * {@inheritdoc}
  297. */
  298. public function getCacheContexts() {
  299. $contexts = [];
  300. if ($this->options['expose_sort_order']) {
  301. // The sort order query arg is just important in case there is a exposed
  302. // sort order.
  303. $has_exposed_sort_handler = FALSE;
  304. /** @var \Drupal\views\Plugin\views\sort\SortPluginBase $sort_handler */
  305. foreach ($this->displayHandler->getHandlers('sort') as $sort_handler) {
  306. if ($sort_handler->isExposed()) {
  307. $has_exposed_sort_handler = TRUE;
  308. }
  309. }
  310. if ($has_exposed_sort_handler) {
  311. $contexts[] = 'url.query_args:sort_order';
  312. }
  313. }
  314. // Merge in cache contexts for all exposed filters to prevent display of
  315. // cached forms.
  316. foreach ($this->displayHandler->getHandlers('filter') as $filter_hander) {
  317. if ($filter_hander->isExposed()) {
  318. $contexts = Cache::mergeContexts($contexts, $filter_hander->getCacheContexts());
  319. }
  320. }
  321. return $contexts;
  322. }
  323. /**
  324. * {@inheritdoc}
  325. */
  326. public function getCacheTags() {
  327. return [];
  328. }
  329. }
  330. /**
  331. * @}
  332. */