Ajouter un commentaire

Soumis par Jesse (non vérifié) le 20/10/2017 à 14:11 - Permalien

Hi,

I have following code, could you tell me why it's not working?
I want to filter the view based on the node created time.

/**
* Implements hook_form_FORM_ID_alter().
*/
function custom_views_filter_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
if (isset($form['#id']) && $form['#id'] == 'views-exposed-form-news-block-1') {
$options = &drupal_static(__FUNCTION__);
if (is_null($options)) {
$cid = 'custom_views_filter:article:created';
$data = \Drupal::cache()->get($cid);
if (!$data) {
$options = [];
$options['all'] = new TranslatableMarkup('- All -');
$query = \Drupal::entityQuery('node');
$query->condition('type', 'article')
->condition('status', 1)
->sort('created', 'ASC');
$result = $query->execute();
if ($result) {
$nodes = \Drupal\node\Entity\Node::loadMultiple($result);
foreach ($nodes as $node) {
$date = $node->getCreatedTime();
if ($date) {
$year = \Drupal::service('date.formatter')->format($date, 'html_year');
if (!isset($options[$year])) {
$options[$year] = $year;
}
}
}
}

$cache_tags = ['node:article:created'];
\Drupal::cache()->set($cid, $options, CacheBackendInterface::CACHE_PERMANENT, $cache_tags);
}
else {
$options = $data->data;
}

}
// kint($options);

$form['year'] = [
'#type' => 'select',
'#options' => $options,
'#size' => NULL,
'#default_value' => '2017',
];
}
}