Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- services:
- event_countdown.date_calculator:
- class: Drupalevent_countdownDateCalculator
- event_countdown.content:
- defaults:
- _title: 'Event Countdown'
- requirements:
- _permission: 'access content'
- options:
- no_cache: 'TRUE'
- <?php
- namespace Drupalevent_countdown;
- class DateCalculator {
- // forms the block's output based on given date
- public function daysUntilEventStarts($date) {
- // get difference in days between now and the given date
- $difference = $this->getDifferenceInDaysFromCurrentDate($date);
- // if event date is in the future
- if($difference >= 1) {
- return "Days left until the event starts: " . $difference;
- // if event date and current date are on the same day
- } else if($difference == 0) {
- return "The event is in progress.";
- // if event date is in the past
- } else {
- return "The event has already ended.";
- }
- }
- // calculates difference in days between now and given date
- public function getDifferenceInDaysFromCurrentDate($date) {
- // current time
- $now = time();
- // event datetime field converted to timestamp
- $event_date = strtotime($date);
- // timestamp difference
- $difference = $event_date - $now;
- // timestamp difference rounded down to days
- return round($difference / (60 * 60 * 24));
- }
- }
- <?php
- namespace Drupalevent_countdownPluginBlock;
- use DrupalCoreBlockBlockBase;
- use SymfonyComponentDependencyInjectionContainerInterface;
- use Drupalevent_countdownDateCalculator;
- /**
- * Provides an event countdown block.
- *
- * @Block(
- * id = "event_countdown_block",
- * admin_label = @Translation("Event countdown block"),
- * category = @Translation("Event countdown block"),
- * )
- */
- class EventCountdownBlock extends BlockBase {
- protected $dateCalculator;
- public function __construct(DateCalculator $dateCalculator) {
- $this->dateCalculator = $dateCalculator;
- }
- public static function create(ContainerInterface $container) {
- return new static($container->get('event_countdown.date_calculator'));
- }
- public function build() {
- // get current node based on route
- $node = Drupal::routeMatch()->getParameter('node');
- //check whether node type equals 'event' - if it does, get text output, otherwise display an error message
- if($node->getType() == "event") {
- // get datetime value from node
- $date = $node->field_event_date->value;
- // call service method to calculate difference in days
- $output = $this->dateCalculator->daysUntilEventStarts($date);
- } else {
- // display error
- $output = "Woops! This block is intended only for event pages.";
- }
- return array(
- // output
- '#markup' => $output,
- // prevent block caching
- '#cache' => [
- 'max-age' => 0,
- ],
- );
- }
- }
Add Comment
Please, Sign In to add comment