You are here

class DateFilter in Visitors 8.2

Hierarchy

Expanded class hierarchy of DateFilter

1 file declares its use of DateFilter
Referers.php in src/Form/Referers.php

File

src/Form/DateFilter.php, line 11

Namespace

Drupal\visitors\Form
View source
class DateFilter extends FormBase {
  protected $_order = array(
    'month',
    'day',
    'year',
  );

  /**
   * @return array
   */
  protected function _getOrder() {
    return $this->_order;
  }
  public function getFormID() {
    return 'visitors_date_filter_form';
  }

  /**
   * Set to session info default values for visitors date filter.
   */
  protected function _setSessionDateRange() {
    if (!isset($_SESSION['visitors_from'])) {
      $_SESSION['visitors_from'] = array(
        'month' => date('n'),
        'day' => 1,
        'year' => date('Y'),
      );
    }
    if (!isset($_SESSION['visitors_to'])) {
      $_SESSION['visitors_to'] = array(
        'month' => date('n'),
        'day' => date('j'),
        'year' => date('Y'),
      );
    }
  }
  public function buildForm(array $form, FormStateInterface $form_state) {
    $this
      ->_setSessionDateRange();
    $from = DrupalDateTime::createFromArray($_SESSION['visitors_from']);
    $to = DrupalDateTime::createFromArray($_SESSION['visitors_to']);
    $form = array();
    $form['visitors_date_filter'] = array(
      '#collapsed' => FALSE,
      '#collapsible' => FALSE,
      '#description' => t('Choose date range'),
      '#title' => t('Date filter'),
      '#type' => 'fieldset',
    );
    $form['visitors_date_filter']['from'] = array(
      '#date_part_order' => $this
        ->_getOrder(),
      '#date_timezone' => date_default_timezone_get(),
      '#default_value' => $from,
      '#element_validate' => array(
        array(
          $this,
          'datelistValidate',
        ),
      ),
      '#process' => array(
        array(
          $this,
          'formProcessDatelist',
        ),
      ),
      '#title' => t('From'),
      '#type' => 'datelist',
      '#value_callback' => array(
        $this,
        'datelistValueCallback',
      ),
    );
    $form['visitors_date_filter']['to'] = array(
      '#date_part_order' => $this
        ->_getOrder(),
      '#date_timezone' => date_default_timezone_get(),
      '#default_value' => $to,
      '#element_validate' => array(
        array(
          $this,
          'datelistValidate',
        ),
      ),
      '#process' => array(
        array(
          $this,
          'formProcessDatelist',
        ),
      ),
      '#title' => t('To'),
      '#type' => 'datelist',
      '#value_callback' => array(
        $this,
        'datelistValueCallback',
      ),
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
    );
    return $form;
  }
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $fromvalue = $form_state
      ->getValue('from');
    $tovalue = $form_state
      ->getValue('to');
    $from = array();
    $to = array();
    $from['month'] = (int) $fromvalue
      ->format('m');
    $from['day'] = (int) $fromvalue
      ->format('d');
    $from['year'] = (int) $fromvalue
      ->format('y');
    $to['month'] = (int) $tovalue
      ->format('m');
    $to['day'] = (int) $tovalue
      ->format('d');
    $to['year'] = (int) $tovalue
      ->format('y');
    $error_message = $this
      ->t('The specified date is invalid.');
    if (!checkdate($from['month'], $from['day'], $from['year'])) {
      return $this
        ->setFormError('from', $form_state, $error_message);
    }
    if (!checkdate($to['month'], $to['day'], $to['year'])) {
      return $this
        ->setFormError('to', $form_state, $error_message);
    }
    $from = mktime(0, 0, 0, $from['month'], $from['day'], $from['year']);
    $to = mktime(23, 59, 59, $to['month'], $to['day'], $to['year']);
    if ((int) $from <= 0) {
      return $this
        ->setFormError('from', $form_state, $error_message);
    }
    if ((int) $to <= 0) {
      return $this
        ->setFormError('to', $form_state, $error_message);
    }
    if ($from > $to) {
      return $this
        ->setFormError('from', $form_state, $error_message);
    }
  }
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $from = $form_state
      ->getValue('from');
    $to = $form_state
      ->getValue('to');
    $_SESSION['visitors_from'] = array(
      'month' => $from
        ->format('n'),
      'day' => $from
        ->format('j'),
      'year' => $from
        ->format('Y'),
    );
    $_SESSION['visitors_to'] = array(
      'month' => $to
        ->format('n'),
      'day' => $to
        ->format('j'),
      'year' => $to
        ->format('Y'),
    );
  }

  /**
   * Validates the date type to prevent invalid dates (e.g., February 30,
   * 2006).
   *
   * If the date is valid, the date is set in the form as a string
   * using the format designated in __toString().
   */
  public function datelistValidate($element, FormStateInterface $form_state) {
    $input_exists = FALSE;
    $input = NestedArray::getValue($form_state
      ->getValues(), $element['#parents'], $input_exists);
    if (!$input_exists) {
      return;
    }

    // If there's empty input, set an error.
    if (empty($input['year']) || empty($input['month']) || empty($input['day'])) {
      $form_state
        ->setError($element, $this
        ->t('The %field date is required.'));
      return;
    }
    if (!checkdate($input['month'], $input['day'], $input['year'])) {
      $this
        ->setError($element, $this
        ->t('The specified date is invalid.'));
      return;
    }
    $date = DrupalDateTime::createFromArray($input);
    if ($date instanceof DrupalDateTime && !$date
      ->hasErrors()) {
      $form_state
        ->setValueForElement($element, $date);
      return;
    }
    $form_state
      ->setError($element, $this
      ->t('The %field date is invalid.'));
  }

  /**
   * Element value callback for datelist element.
   */
  public function datelistValueCallback($element, $input = FALSE, &$form_state = array()) {
    $parts = $this
      ->_getOrder();
    $return = array_fill_keys($parts, '');
    foreach ($parts as $part) {
      $return[$part] = $input[$part];
    }
    return $return;
  }
  public function formProcessDatelist($element, &$form_state) {
    if (empty($element['#value']['month']) || empty($element['#value']['day']) || empty($element['#value']['year'])) {
      $element['#value'] = array(
        'month' => $element['#default_value']
          ->format('n'),
        'day' => $element['#default_value']
          ->format('j'),
        'year' => $element['#default_value']
          ->format('Y'),
      );
    }
    $element['#tree'] = TRUE;

    // Output multi-selector for date.
    foreach ($this
      ->_getOrder() as $part) {
      switch ($part) {
        case 'month':
          $options = DateHelper::monthNamesAbbr(TRUE);
          $title = t('Month');
          break;
        case 'day':
          $options = DateHelper::days(TRUE);
          $title = t('Day');
          break;
        case 'year':
          $options = DateHelper::years($this
            ->_getMinYear(), date('Y'), TRUE);
          $title = t('Year');
          break;
      }
      $element['#attributes']['title'] = $title;
      $element[$part] = array(
        '#attributes' => $element['#attributes'],
        '#options' => $options,
        '#required' => $element['#required'],
        '#title' => $title,
        '#title_display' => 'invisible',
        '#type' => 'select',
        '#value' => (int) $element['#value'][$part],
      );
    }
    return $element;
  }

  /**
   * Get min year for date fields visitors date filter.
   * Min year - min value from {visitors} table.
   *
   * @return int min year
   */
  protected function _getMinYear() {
    $query = \Drupal::database()
      ->select('visitors');
    $query
      ->addExpression('MIN(visitors_date_time)');
    $min_timestamp = $query
      ->execute()
      ->fetchField();
    $timezone = date_default_timezone_get();
    return \Drupal::service('date.formatter')
      ->format($min_timestamp, 'custom', 'Y', $timezone);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DateFilter::$_order protected property
DateFilter::buildForm public function Form constructor. Overrides FormInterface::buildForm 1
DateFilter::datelistValidate public function Validates the date type to prevent invalid dates (e.g., February 30, 2006).
DateFilter::datelistValueCallback public function Element value callback for datelist element.
DateFilter::formProcessDatelist public function
DateFilter::getFormID public function 1
DateFilter::submitForm public function Form submission handler. Overrides FormInterface::submitForm 1
DateFilter::validateForm public function Form validation handler. Overrides FormBase::validateForm
DateFilter::_getMinYear protected function Get min year for date fields visitors date filter. Min year - min value from {visitors} table.
DateFilter::_getOrder protected function
DateFilter::_setSessionDateRange protected function Set to session info default values for visitors date filter.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormInterface::getFormId public function Returns a unique string identifying the form. 236
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.