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\Datetime\Entity\DateFormat;
- use Drupal\Core\Form\FormStateInterface;
- use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
- use Drupal\Core\StringTranslation\TranslatableMarkup;
- use Symfony\Component\DependencyInjection\ContainerInterface;
- /**
- * Provides a block that displays the current date.
- */
- #[Block(
- id: "current_date_block",
- admin_label: new TranslatableMarkup("Current date")
- )]
- 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) {
- return new static(
- $configuration,
- $plugin_id,
- $plugin_definition,
- $container->get('date.formatter')
- );
- }
- public function defaultConfiguration() {
- return [
- 'date_format' => 'medium',
- 'label_display' => 'visible',
- ];
- }
- public function blockForm($form, FormStateInterface $form_state) {
- $form['date_format'] = [
- '#type' => 'select',
- '#title' => $this->t('Date format'),
- '#description' => $this->t('Choose the format for displaying the date.'),
- '#options' => $this->getDateFormatOptions(),
- '#default_value' => $this->configuration['date_format'],
- '#required' => TRUE,
- ];
- return $form;
- }
- public function blockSubmit($form, FormStateInterface $form_state) {
- $this->configuration['date_format'] = $form_state->getValue('date_format');
- }
- public function build() {
- $request_time = \Drupal::time()->getRequestTime();
- $format = $this->configuration['date_format'];
- $build = [
- '#type' => 'html_tag',
- '#tag' => 'div',
- '#attributes' => ['class' => ['current-date-block']],
- '#value' => $this->dateFormatter->format($request_time, $format),
- '#cache' => [
- 'max-age' => 0,
- ],
- ];
- return $build;
- }
- protected function getDateFormatOptions() {
- $options = [];
- $date_formats = DateFormat::loadMultiple();
- foreach ($date_formats as $id => $date_format) {
- $options[$id] = $this->t('@label (@format)', [
- '@label' => $date_format->label(),
- '@format' => $date_format->getPattern(),
- ]);
- }
- return $options;
- }
- }
Advertisement