Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- namespace Drupal\current_date_block\Plugin\Block;
- use Drupal\Core\Block\Attribute\Block;
- use Drupal\Core\Block\BlockBase;
- use Drupal\Core\Block\BlockPluginInterface;
- use Drupal\Core\Form\FormStateInterface;
- use Drupal\Core\StringTranslation\TranslatableMarkup;
- /**
- * Provides a current date block.
- */
- #[Block(
- id: 'current_date_block',
- admin_label: new TranslatableMarkup('Current date'),
- )]
- final class CurrentDateBlock extends BlockBase {
- /**
- * {@inheritdoc}
- */
- public function defaultConfiguration(): array {
- return [
- 'label_display' => BlockPluginInterface::BLOCK_LABEL_VISIBLE,
- 'date_format' => 'Y-m-d',
- ] + parent::defaultConfiguration();
- }
- /**
- * {@inheritdoc}
- */
- public function build(): array {
- $format = $this->configuration['date_format'] ?? 'Y-m-d';
- return [
- '#plain_text' => date($format),
- ];
- }
- /**
- * {@inheritdoc}
- */
- public function blockForm($form, FormStateInterface $form_state): array {
- $form = parent::blockForm($form, $form_state);
- $form['date_format'] = [
- '#type' => 'textfield',
- '#title' => $this->t('Date format'),
- '#description' => $this->t('PHP date format string, for example: Y-m-d or d.m.Y H:i'),
- '#default_value' => $this->configuration['date_format'] ?? 'Y-m-d',
- '#required' => TRUE,
- '#maxlength' => 128,
- ];
- return $form;
- }
- /**
- * {@inheritdoc}
- */
- public function blockSubmit($form, FormStateInterface $form_state): void {
- parent::blockSubmit($form, $form_state);
- $this->configuration['date_format'] = $form_state->getValue('date_format');
- }
- /**
- * {@inheritdoc}
- */
- public function getCacheMaxAge(): int {
- return 0;
- }
- }
Advertisement