What's the Current Year III

Creating links based on the year


In the previous article, we looked at how to control the content on a page based on the year. In this one we'll see a way to create links based on the year.


MODX logo

The Problem

Suppose that you have a list of current events. You want to keep the events for the previous year available so your users can look at the history of events and you also want to show next years events. You have a separate event page for each year. You could certainly edit the links at the beginning of the year, but why not automate the process with a fairly simple snippet.


The Solution

You'll want to have the alias of each resource contain the year like this: events2019, events2020, events2021.

Now, you can put these tags where you want the links to appear:

<br>
<h3>Events</h3>

<ul>
    <li><a href="[[!Events? $year=`previous`]]">Last Year's Events</a></li>
    <li><a href="[[!Events? $year=`current`]]">This Year's Events</a></li>
    <li><a href="[[!Events? $year=`next`]]">Next Year's Events</a></li>
</ul>

It's a good idea to display a "Coming Soon" or "No Events Yet" message on the following year's page if there are no events to show. You can do that by wrapping the snippet (e.g., getResources or pdoResources) with an output modifier that shows the message if the results are empty:

[[!getResources:default=`No Events Found`?
    (other getResources params here)
]]

(Note that the solution above won't work if you use the &toPlaceholder property.)

 

Now create a snippet called Events with this code:

/* Events snippet */
$year = date("Y");

$whichYear = $modx->getOption('year', $scriptProperties);

switch($whichYear) {
    case 'previous':
        $yearToShow = $year - 1;
        break;

    case 'current':
        $yearToShow = $year;
        break;

    case 'next':
        $yearToShow = $year + 1;
        break;
    default:
        $modx->log(modX::LOG_LEVEL_ERROR,
            '[events snippet] invalid year property');
}

$alias = 'events' . $yearToShow;
$resource = $modx->getObject('modResource',
    array('alias' => 'events' . $yearToShow));

if ($resource) {
    $docId = $resource->get('id');
} else {
    $modx->log(modX::LOG_LEVEL_ERROR,
        '[events snippet] resource with alias ' .
        $alias . 'not found: ');
}

$url = $modx->makeUrl($docId, "", "", "full");
return $url;

The links will always point to the correct pages, but be sure to create the events pages being linked to before the beginning of each year.


Coming Up

There might be situations where you want to automatically forward the user to a year-based page without requiring them to click on anything. We'll see how to do that in the next article.



Looking for high-quality, MODX-friendly hosting? As of May 2016, Bob's Guides is hosted at A2 hosting. (More information in the box below.)



Comments (0)


Please login to comment.

  (Login)