Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Drupal\current_date_block\Plugin\Block;
- use Drupal\Core\Block\Attribute\Block;
- use Drupal\Core\Block\BlockBase;
- use Drupal\Core\Form\FormStateInterface;
- use Drupal\Core\StringTranslation\TranslatableMarkup;
- #[Block(
- id: "current_date_block",
- admin_label: new TranslatableMarkup("Current date"),
- category: new TranslatableMarkup("Custom")
- )]
- class CurrentDateBlock extends BlockBase {
- public function defaultConfiguration(): array {
- return [
- 'date_format' => 'Y-m-d H:i:s',
- ];
- }
- public function blockForm($form, FormStateInterface $form_state): array {
- $form['date_format'] = [
- '#type' => 'textfield',
- '#title' => $this->t('Date format'),
- '#description' => $this->t('Enter a PHP date format string (e.g. @example). See <a href=":url">PHP date documentation</a>.', [
- '@example' => 'Y-m-d H:i:s',
- ':url' => 'https://www.php.net/manual/en/datetime.format.php',
- ]),
- '#default_value' => $this->configuration['date_format'],
- '#required' => TRUE,
- ];
- return $form;
- }
- public function blockSubmit($form, FormStateInterface $form_state): void {
- $this->configuration['date_format'] = $form_state->getValue('date_format');
- }
- public function blockValidate($form, FormStateInterface $form_state): void {
- $format = $form_state->getValue('date_format');
- $now = new \DateTime();
- $result = $now->format($format);
- if ($result === FALSE) {
- $form_state->setErrorByName('date_format', $this->t('Invalid date format string.'));
- }
- }
- public function build(): array {
- $now = new \DateTime();
- return [
- '#markup' => $this->t('Current date and time: @date', [
- '@date' => $now->format($this->configuration['date_format']),
- ]),
- ];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment