single_datetime_exposed.module in Single DateTimePicker 8
Main module file single_datetime_exposed.
File
modules/single_datetime_exposed/single_datetime_exposed.moduleView source
<?php
/**
* @file
* Main module file single_datetime_exposed.
*/
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\single_datetime\AttributeHelper;
/**
* Implements hook_help().
*/
function single_datetime_exposed_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.single_datetime_exposed':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('Date time picker attached to all Views exposed date fields automatically.');
return $output;
}
}
/**
* Implements hook_form_BASE_FORM_ID_alter().
*/
function single_datetime_exposed_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
/** @var \Drupal\views\ViewExecutable $view */
$view = $form_state
->getStorage()['view'];
if ($view->preview === NULL) {
$filters = $view
->getHandlers('filter');
// Use default template from helper.
$attributes = AttributeHelper::defaultWidget();
$active = FALSE;
foreach ($filters as $id => $filter) {
// Only take filters which are exposed and date based.
// Only handle date based value, no offset exposed dates.
if (!empty($filter['exposed']) && $filter['value']['type'] === 'date' && ($filter['plugin_id'] === 'date' || $filter['plugin_id'] === 'search_api_date')) {
$active = TRUE;
$field_name = $filter['id'];
// Based on selected filters attach attributes on proper place.
switch ($filter['operator']) {
case 'between':
case 'not between':
$form[$field_name]['min']['#attributes'] = $attributes;
$form[$field_name]['max']['#attributes'] = $attributes;
// Adjust titles.
$field_title = $form[$field_name]['min']['#title'];
$form[$field_name]['min']['#title'] = $field_title . ' ( ' . t('From') . ' )';
$form[$field_name]['max']['#title'] = $field_title . ' ( ' . t('To') . ' )';
// On between filters when end value is empty, sometimes filters
// are not working. So set end value.
$input = $form_state
->getUserInput();
if (!empty($input[$field_name]['min']) && empty($input[$field_name]['max'])) {
$timestamp = strtotime($input[$field_name]['min']) + 86400;
$input[$field_name]['max'] = date('Y-m-d h:i:s', $timestamp);
$form_state
->setUserInput($input);
}
break;
default:
$form[$field_name]['#attributes'] = $attributes;
}
}
}
// If we have found filters. Attach library.
if ($active) {
$form['#attached']['library'][] = 'single_datetime/datetimepicker';
}
}
}
Functions
Name | Description |
---|---|
single_datetime_exposed_form_views_exposed_form_alter | Implements hook_form_BASE_FORM_ID_alter(). |
single_datetime_exposed_help | Implements hook_help(). |