Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- use Drupal\Core\Cache\CacheBackendInterface;
- use Drupal\Core\StringTranslation\TranslatableMarkup;
- use Drupal\Core\Form\FormStateInterface;
- use Drupal\Core\Entity\EntityInterface;
- /**
- * Implements hook_form_FORM_ID_alter().
- */
- function myModule_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
- if (isset($form['#id']) && $form['#id'] == 'views-exposed-form-ContentType-DisplayId') {
- // If date filter set change if to select list of years.
- if (isset($form['field_date_value'])) {
- // Get options from cache.
- $options = &drupal_static(__FUNCTION__);
- if (is_null($options)) {
- // Set up cid.
- $cid = 'myModule:ContentType:year';
- // Get data from cache.
- $data = \Drupal::cache()->get($cid);
- if (!$data) {
- $options[''] = new TranslatableMarkup('Year');
- $query = \Drupal::entityQuery('node');
- $query->condition('type', 'ContentType')
- ->condition('status', 1)
- ->sort('field_date', 'ASC');
- $result = $query->execute();
- if ($result) {
- $nodes = Node::loadMultiple($result);
- foreach ($nodes as $key => $node) {
- if ($node->hasField('field_date')) {
- $date = $node->field_date->value;
- if ($date) {
- $date = new DrupalDateTime($date, new DateTimeZone('UTC'));
- $year = $date->format('Y');
- if (!isset($options[$year])) {
- $options['.*' . $year] = $year;
- }
- }
- }
- }
- }
- // Cache tag.
- $cache_tags = ['node:ContentType:year'];
- // Set cache.
- \Drupal::cache()
- ->set($cid, $options, CacheBackendInterface::CACHE_PERMANENT, $cache_tags);
- }
- else {
- $options = $data->data;
- }
- }
- // Change the filter to select.
- $form['field_date_value'] = [
- '#type' => 'select',
- '#options' => $options,
- '#size' => NULL,
- '#default_value' => '',
- ];
- }
- }
- }
- /**
- * Implements hook_ENTITY_TYPE_presave().
- */
- function myModule_node_presave(EntityInterface $entity) {
- $bundle = $entity->bundle();
- if ($bundle == 'ContentType') {
- // Check if a ContentType updated has a new year, and invalidate the.
- // options cached used in the custom views filter for filtering by year.
- $cid = 'myModule:ContentType:year';
- $data = \Drupal::cache()->get($cid);
- if ($data) {
- if ($entity->hasField('field_date')) {
- $options = $data->data;
- $date = $entity->field_date->value;
- if ($date) {
- $date = new DrupalDateTime($date, new DateTimeZone('UTC'));
- $year = $date->format('Y');
- if (!isset($options['.*' . $year])) {
- Cache::invalidateTags(['node:ContentType:year']);
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement