Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- namespace Drupal\current_date\Plugin\Block;
- use Drupal\Core\Block\Attribute\Block;
- use Drupal\Core\Block\BlockBase;
- use Drupal\Core\Datetime\DrupalDateTime;
- use Drupal\Core\Form\FormStateInterface;
- use Drupal\Core\StringTranslation\TranslatableMarkup;
- /**
- * Provides a block that displays the current date.
- */
- #[Block(
- id: 'current_date_block',
- admin_label: new TranslatableMarkup('Current date'),
- category: new TranslatableMarkup('Custom'),
- )]
- final class CurrentDateBlock extends BlockBase {
- /**
- * {@inheritdoc}
- */
- public function defaultConfiguration(): array {
- return [
- 'date_format' => 'd.m.Y',
- ] + parent::defaultConfiguration();
- }
- /**
- * {@inheritdoc}
- */
- public function blockForm($form, FormStateInterface $form_state): array {
- $form['date_format'] = [
- '#type' => 'textfield',
- '#title' => $this->t('Date format'),
- '#description' => $this->t('A PHP date format string. Example: %example.', [
- '%example' => 'd.m.Y H:i',
- ]),
- '#default_value' => $this->configuration['date_format'],
- '#required' => TRUE,
- ];
- return $form;
- }
- /**
- * {@inheritdoc}
- */
- public function blockSubmit($form, FormStateInterface $form_state): void {
- $this->configuration['date_format'] = $form_state->getValue('date_format');
- }
- /**
- * {@inheritdoc}
- */
- public function build(): array {
- $formatted = (new DrupalDateTime('now'))->format($this->configuration['date_format']);
- return [
- '#markup' => $formatted,
- '#cache' => [
- 'max-age' => 0,
- ],
- ];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment