contacts_events-8.x-1.x-dev/src/Plugin/EntityReferenceSelection/EventSelection.php

src/Plugin/EntityReferenceSelection/EventSelection.php
<?php

namespace Drupal\contacts_events\Plugin\EntityReferenceSelection;

use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
use Drupal\Core\Form\FormStateInterface;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Optionally filter events by past or future.
 *
 * @EntityReferenceSelection(
 *   id = "default:contacts_event",
 *   label = @Translation("Event selection"),
 *   entity_types = {"contacts_event"},
 *   group = "default",
 *   weight = 1
 * )
 */
class EventSelection extends DefaultSelection {

  /**
   * The time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $plugin = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $plugin->time = $container->get('datetime.time');
    return $plugin;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'date_filter' => NULL,
      'auto_create' => FALSE,
      'sort' => [
        'field' => 'date.end_value',
        'direction' => 'asc',
      ],
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    // Disable custom sorting and auto creation.
    $form['sort']['#access'] = FALSE;
    $form['auto_create']['#access'] = FALSE;

    // Add our date filter.
    $form['date_filter'] = [
      '#type' => 'select',
      '#title' => $this->t('Date filter'),
      '#required' => FALSE,
      '#default_value' => $this->configuration['date_filter'],
      '#options' => [
        'past' => 'Past',
        'future' => 'Current and future',
      ],
      '#empty_option' => $this->t('All events'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
    $query = parent::buildEntityQuery($match, $match_operator);

    // Filter by date if configured.
    if (!empty($this->configuration['date_filter'])) {
      $date_filter = $this->configuration['date_filter'];

      $operator = '>=';
      if ($date_filter == 'past') {
        $operator = '<';
      }

      $request_time = new DrupalDateTime();
      $request_time->setTimestamp($this->time->getRequestTime());
      $query->condition('date.end_value', $request_time->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT), $operator);
    }

    return $query;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc