Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Drupal\current_date\Plugin\Block;
- use Drupal\Core\Block\Attribute\Block;
- use Drupal\Core\Block\BlockBase;
- use Drupal\Core\Datetime\DateFormatterInterface;
- use Drupal\Core\Form\FormStateInterface;
- use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
- use Drupal\Core\StringTranslation\TranslatableMarkup;
- use Symfony\Component\DependencyInjection\ContainerInterface;
- #[Block(
- id: "current_date",
- admin_label: new TranslatableMarkup("Current date"),
- category: new TranslatableMarkup("Custom")
- )]
- class CurrentDateBlock extends BlockBase implements ContainerFactoryPluginInterface {
- public function __construct(
- array $configuration,
- $plugin_id,
- $plugin_definition,
- protected DateFormatterInterface $dateFormatter,
- ) {
- parent::__construct($configuration, $plugin_id, $plugin_definition);
- }
- public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
- return new static(
- $configuration,
- $plugin_id,
- $plugin_definition,
- $container->get('date.formatter'),
- );
- }
- public function defaultConfiguration(): array {
- return [
- 'date_format' => 'Y-m-d',
- ];
- }
- 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 as used by <a href=":url">date()</a>.', [
- ':url' => 'https://www.php.net/manual/en/datetime.format.php',
- ]),
- '#default_value' => $this->configuration['date_format'],
- ];
- return $form;
- }
- public function blockSubmit($form, FormStateInterface $form_state): void {
- $this->configuration['date_format'] = $form_state->getValue('date_format');
- }
- public function build(): array {
- $date = $this->dateFormatter->format(time(), 'custom', $this->configuration['date_format']);
- return [
- '#markup' => '<div class="current-date">' . $this->t('Today is @date', ['@date' => $date]) . '</div>',
- ];
- }
- }
Advertisement