xandeadx

Big Pickle (free)

Jun 26th, 2026 (edited)
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.81 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Drupal\current_date_block\Plugin\Block;
  4.  
  5. use Drupal\Core\Block\Attribute\Block;
  6. use Drupal\Core\Block\BlockBase;
  7. use Drupal\Core\Form\FormStateInterface;
  8. use Drupal\Core\StringTranslation\TranslatableMarkup;
  9.  
  10. #[Block(
  11.  id: "current_date_block",
  12.   admin_label: new TranslatableMarkup("Current date"),
  13.   category: new TranslatableMarkup("Custom")
  14. )]
  15. class CurrentDateBlock extends BlockBase {
  16.  
  17.   public function defaultConfiguration(): array {
  18.     return [
  19.       'date_format' => 'Y-m-d H:i:s',
  20.     ];
  21.   }
  22.  
  23.   public function blockForm($form, FormStateInterface $form_state): array {
  24.     $form['date_format'] = [
  25.       '#type' => 'textfield',
  26.       '#title' => $this->t('Date format'),
  27.       '#description' => $this->t('Enter a PHP date format string (e.g. @example). See <a href=":url">PHP date documentation</a>.', [
  28.         '@example' => 'Y-m-d H:i:s',
  29.         ':url' => 'https://www.php.net/manual/en/datetime.format.php',
  30.       ]),
  31.       '#default_value' => $this->configuration['date_format'],
  32.       '#required' => TRUE,
  33.     ];
  34.     return $form;
  35.   }
  36.  
  37.   public function blockSubmit($form, FormStateInterface $form_state): void {
  38.     $this->configuration['date_format'] = $form_state->getValue('date_format');
  39.   }
  40.  
  41.   public function blockValidate($form, FormStateInterface $form_state): void {
  42.     $format = $form_state->getValue('date_format');
  43.     $now = new \DateTime();
  44.     $result = $now->format($format);
  45.     if ($result === FALSE) {
  46.       $form_state->setErrorByName('date_format', $this->t('Invalid date format string.'));
  47.     }
  48.   }
  49.  
  50.   public function build(): array {
  51.     $now = new \DateTime();
  52.     return [
  53.       '#markup' => $this->t('Current date and time: @date', [
  54.         '@date' => $now->format($this->configuration['date_format']),
  55.       ]),
  56.     ];
  57.   }
  58.  
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment