Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- namespace Drupal\example\Plugin\Block;
- use Drupal\Component\Datetime\TimeInterface;
- use Drupal\Core\Block\Attribute\Block;
- use Drupal\Core\Block\BlockBase;
- use Drupal\Core\Datetime\DateFormatterInterface;
- use Drupal\Core\Entity\EntityTypeManagerInterface;
- use Drupal\Core\Form\FormStateInterface;
- use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
- use Drupal\Core\StringTranslation\TranslatableMarkup;
- use Symfony\Component\DependencyInjection\ContainerInterface;
- /**
- * Provides a block displaying the current date.
- */
- #[Block(
- id: self::ID,
- admin_label: new TranslatableMarkup('Current date'),
- )]
- final class CurrentDateBlock extends BlockBase implements ContainerFactoryPluginInterface {
- public const string ID = 'example_current_date';
- /**
- * Cache max-age (seconds). The current date is time-dependent.
- */
- private const int CACHE_MAX_AGE = 60;
- /**
- * Creates a new CurrentDateBlock instance.
- *
- * @param array $configuration
- * The plugin configuration.
- * @param string $plugin_id
- * The plugin ID.
- * @param mixed $plugin_definition
- * The plugin definition.
- * @param \Drupal\Core\Datetime\DateFormatterInterface $dateFormatter
- * The date formatter service.
- * @param \Drupal\Component\Datetime\TimeInterface $time
- * The time service (provides the request time).
- * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
- * The entity type manager (to load date format entities).
- */
- public function __construct(
- array $configuration,
- $plugin_id,
- $plugin_definition,
- protected DateFormatterInterface $dateFormatter,
- protected TimeInterface $time,
- protected EntityTypeManagerInterface $entityTypeManager,
- ) {
- parent::__construct($configuration, $plugin_id, $plugin_definition);
- }
- /**
- * {@inheritdoc}
- */
- public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
- return new self(
- $configuration,
- $plugin_id,
- $plugin_definition,
- $container->get('date.formatter'),
- $container->get('datetime.time'),
- $container->get('entity_type.manager'),
- );
- }
- /**
- * {@inheritdoc}
- */
- public function defaultConfiguration(): array {
- return [
- 'date_format' => 'medium',
- 'custom_format' => '',
- ] + parent::defaultConfiguration();
- }
- /**
- * {@inheritdoc}
- */
- public function blockForm($form, FormStateInterface $form_state): array {
- $formats = [];
- foreach ($this->entityTypeManager->getStorage('date_format')->loadMultiple() as $machine_name => $format) {
- $formats[$machine_name] = $format->label();
- }
- $form['date_format'] = [
- '#type' => 'select',
- '#title' => $this->t('Date format'),
- '#description' => $this->t('Choose a date format defined at <a href=":url">Date and time formats</a>.', [
- ':url' => '/admin/config/regional/date-time',
- ]),
- '#options' => $formats,
- '#default_value' => $this->configuration['date_format'],
- '#required' => TRUE,
- ];
- $form['custom_format'] = [
- '#type' => 'textfield',
- '#title' => $this->t('Custom format'),
- '#description' => $this->t('A PHP date format string (e.g. <em>d.m.Y</em>). Used when "Date format" is not applicable. See the <a href=":url">PHP manual</a> for available options.', [
- ':url' => 'https://www.php.net/manual/datetime.format.php',
- ]),
- '#default_value' => $this->configuration['custom_format'],
- '#states' => [
- 'visible' => [
- ':input[name="settings[date_format]"]' => ['value' => 'custom'],
- ],
- ],
- ];
- return $form;
- }
- /**
- * {@inheritdoc}
- */
- public function blockSubmit($form, FormStateInterface $form_state): void {
- $this->configuration['date_format'] = $form_state->getValue('date_format');
- $this->configuration['custom_format'] = $form_state->getValue('custom_format');
- }
- /**
- * {@inheritdoc}
- */
- public function build(): array {
- $date_format = $this->configuration['date_format'];
- $format_type = $date_format === 'custom' ? 'custom' : $date_format;
- $formatted = $this->dateFormatter->format(
- $this->time->getRequestTime(),
- $format_type,
- $this->configuration['custom_format'],
- );
- return [
- '#plain_text' => $formatted,
- '#cache' => [
- 'contexts' => ['timezone'],
- 'max-age' => self::CACHE_MAX_AGE,
- ],
- ];
- }
- }
Advertisement