Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Drupal\my_module\Plugin\Block;
- use Drupal\Core\Block\BlockBase;
- use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
- use Symfony\Component\DependencyInjection\ContainerInterface;
- use Drupal\Core\Datetime\DateFormatterInterface;
- use Drupal\Component\Datetime\TimeInterface;
- use Drupal\Core\Form\FormStateInterface;
- /**
- * Предоставляет блок 'Текущий день'.
- *
- * @Block(
- * id = "current_day_block",
- * admin_label = @Translation("Текущий день"),
- * category = @Translation("Custom"),
- * )
- */
- class CurrentDayBlock extends BlockBase implements ContainerFactoryPluginInterface {
- /**
- * Сервис форматирования даты.
- *
- * @var \Drupal\Core\Datetime\DateFormatterInterface
- */
- protected $dateFormatter;
- /**
- * Сервис времени.
- *
- * @var \Drupal\Component\Datetime\TimeInterface
- */
- protected $time;
- /**
- * Конструктор плагина блока.
- */
- public function __construct(
- array $configuration,
- $plugin_id,
- $plugin_definition,
- DateFormatterInterface $date_formatter,
- TimeInterface $time
- ) {
- parent::__construct($configuration, $plugin_id, $plugin_definition);
- $this->dateFormatter = $date_formatter;
- $this->time = $time;
- }
- /**
- * {@inheritdoc}
- */
- public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
- return new static(
- $configuration,
- $plugin_id,
- $plugin_definition,
- $container->get('date.formatter'),
- $container->get('datetime.time')
- );
- }
- /**
- * {@inheritdoc}
- */
- public function defaultConfiguration() {
- // Задаем настройки по умолчанию: формат даты и заголовок блока.
- return [
- 'date_format' => 'l, d.m.Y',
- 'label' => 'Текущий день',
- 'label_display' => TRUE,
- ] + parent::defaultConfiguration();
- }
- /**
- * {@inheritdoc}
- */
- public function blockForm($form, FormStateInterface $form_state) {
- // Добавляем поле настройки формата даты в стандартную форму настройки блока.
- $form['date_format'] = [
- '#type' => 'textfield',
- '#title' => $this->t('Формат даты (PHP DateTime формат)'),
- '#description' => $this->t('Используйте синтаксис PHP. Например: <em>d.m.Y</em> (01.01.2024) или <em>l, j F</em> (Понедельник, 1 Января). <a href="https://www.php.net/manual/ru/datetime.format.php">Документация PHP</a>.'),
- '#default_value' => $this->configuration['date_format'],
- '#required' => TRUE,
- ];
- return $form;
- }
- /**
- * {@inheritdoc}
- */
- public function blockSubmit($form, FormStateInterface $form_state) {
- // Сохраняем значение настройки.
- $this->configuration['date_format'] = $form_state->getValue('date_format');
- }
- /**
- * {@inheritdoc}
- */
- public function build() {
- // Получаем текущее время (timestamp).
- $now = $this->time->getCurrentTime();
- // Форматируем дату с учетом выбранного формата.
- $formatted_date = $this->dateFormatter->format($now, 'custom', $this->configuration['date_format']);
- // Вычисляем количество секунд до полуночи для сброса кэша блока.
- $datetime = new \DateTime();
- $datetime->setTimestamp($now);
- $datetime->setTime(23, 59, 59);
- $seconds_until_midnight = $datetime->getTimestamp() - $now + 1;
- return [
- '#theme' => 'current_day_block',
- '#date' => $formatted_date,
- // Прячем стандартный заголовок, так как мы будем выводить его в шаблоне,
- // ИЛИ можно оставить рендер заголовка через '#title' (смотри пояснения ниже).
- '#attached' => [
- 'library' => [],
- ],
- '#cache' => [
- 'max-age' => $seconds_until_midnight,
- 'contexts' => ['timezone'], // Кэш зависит от часового пояса пользователя
- ],
- ];
- }
- }
Add Comment
Please, Sign In to add comment