Skip to content

Instantly share code, notes, and snippets.

@BERRAMOU
Last active July 8, 2019 14:05
Show Gist options
  • Save BERRAMOU/3a30863ffc158def270b9ec9fcfc3933 to your computer and use it in GitHub Desktop.
Save BERRAMOU/3a30863ffc158def270b9ec9fcfc3933 to your computer and use it in GitHub Desktop.
Filter by year in date even if it has other formats then YYYY, just add the field as exposed filter with regex Operator, and then adapt the bellow code to your case.
<?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']);
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment