Skip to content

Part 2: Event and Template Listeners#

In the first part of this tutorial series, we have created the base structure of our people management package. In further parts, we will use the package of the first part as a basis to directly add new features. In order to explain how event listeners and template works, however, we will not directly adding a new feature to the package by altering it in this part, but we will assume that somebody else created the package and that we want to extend it the “correct” way by creating a plugin.

The goal of the small plugin that will be created in this part is to add the birthday of the managed people. As in the first part, we will not bother with careful validation of the entered date but just make sure that it is a valid date.

Package Functionality#

The package should provide the following possibilities/functions:

  • List person’s birthday (if set) in people list in the ACP
  • Sort people list by birthday in the ACP
  • Add or remove birthday when adding or editing person
  • List person’s birthday (if set) in people list in the front end
  • Sort people list by birthday in the front end

Used Components#

We will use the following package installation plugins:

For more information about the event system, please refer to the dedicated page on events.

Package Structure#

The package will have the following file structure:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
├── eventListener.xml
├── files
│   ├── acp
│   │   └── database
│   │       └── install_com.woltlab.wcf.people.birthday.php
│   └── lib
│       └── system
│           └── event
│               └── listener
│                   ├── BirthdayPersonAddFormListener.class.php
│                   └── BirthdaySortFieldPersonListPageListener.class.php
├── language
│   ├── de.xml
│   └── en.xml
├── package.xml
├── templateListener.xml
└── templates
    ├── __personListBirthday.tpl
    └── __personListBirthdaySortField.tpl

Extending Person Model#

The existing model of a person only contains the person’s first name and their last name (in additional to the id used to identify created people). To add the birthday to the model, we need to create an additional database table column using the database package installation plugin:

files/acp/database/install_com.woltlab.wcf.people.birthday.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php

use wcf\system\database\table\column\DateDatabaseTableColumn;
use wcf\system\database\table\PartialDatabaseTable;

return [
    PartialDatabaseTable::create('wcf1_person')
        ->columns([
            DateDatabaseTableColumn::create('birthday'),
        ]),
];

If we have a Person object, this new property can be accessed the same way as the personID property, the firstName property, or the lastName property from the base package: $person->birthday.

Setting Birthday in ACP#

To set the birthday of a person, we only have to add another form field with an event listener:

files/lib/system/event/listener/BirthdayPersonAddFormListener.class.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php

namespace wcf\system\event\listener;

use wcf\acp\form\PersonAddForm;
use wcf\form\AbstractFormBuilderForm;
use wcf\system\form\builder\container\FormContainer;
use wcf\system\form\builder\field\DateFormField;

/**
 * Handles setting the birthday when adding and editing people.
 *
 * @author  Matthias Schmidt
 * @copyright   2001-2021 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Event\Listener
 */
class BirthdayPersonAddFormListener extends AbstractEventListener
{
    /**
     * @see AbstractFormBuilderForm::createForm()
     */
    protected function onCreateForm(PersonAddForm $form): void
    {
        /** @var FormContainer $dataContainer */
        $dataContainer = $form->form->getNodeById('data');
        $dataContainer->appendChild(
            DateFormField::create('birthday')
                ->label('wcf.person.birthday')
                ->saveValueFormat('Y-m-d')
                ->nullable()
        );
    }
}

registered via

1
2
3
4
5
6
7
<eventlistener name="createForm@wcf\acp\form\PersonAddForm">
  <environment>admin</environment>
  <eventclassname>wcf\acp\form\PersonAddForm</eventclassname>
  <eventname>createForm</eventname>
  <listenerclassname>wcf\system\event\listener\BirthdayPersonAddFormListener</listenerclassname>
  <inherit>1</inherit>
</eventlistener>

in eventListener.xml, see below.

As BirthdayPersonAddFormListener extends AbstractEventListener and as the name of relevant event is createForm, AbstractEventListener internally automatically calls onCreateForm() with the event object as the parameter. It is important to set <inherit>1</inherit> so that the event listener is also executed for PersonEditForm, which extends PersonAddForm.

The language item wcf.person.birthday used in the label is the only new one for this package:

language/de.xml
1
2
3
4
5
6
<?xml version="1.0" encoding="UTF-8"?>
<language xmlns="http://www.woltlab.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd" languagecode="de">
    <category name="wcf.person">
        <item name="wcf.person.birthday"><![CDATA[Geburtstag]]></item>
    </category>
</language>
language/en.xml
1
2
3
4
5
6
<?xml version="1.0" encoding="UTF-8"?>
<language xmlns="http://www.woltlab.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.woltlab.com http://www.woltlab.com/XSD/5.4/language.xsd" languagecode="en">
    <category name="wcf.person">
        <item name="wcf.person.birthday"><![CDATA[Birthday]]></item>
    </category>
</language>

Adding Birthday Table Column in ACP#

To add a birthday column to the person list page in the ACP, we need three parts:

  1. an event listener that makes the birthday database table column a valid sort field,
  2. a template listener that adds the birthday column to the table’s head, and
  3. a template listener that adds the birthday column to the table’s rows.

The first part is a very simple class:

files/lib/system/event/listener/BirthdaySortFieldPersonListPageListener.class.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php

namespace wcf\system\event\listener;

use wcf\page\SortablePage;

/**
 * Makes people's birthday a valid sort field in the ACP and the front end.
 *
 * @author  Matthias Schmidt
 * @copyright   2001-2021 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Event\Listener
 */
class BirthdaySortFieldPersonListPageListener extends AbstractEventListener
{
    /**
     * @see SortablePage::validateSortField()
     */
    public function onValidateSortField(SortablePage $page): void
    {
        $page->validSortFields[] = 'birthday';
    }
}

We use SortablePage as a type hint instead of wcf\acp\page\PersonListPage because we will be using the same event listener class in the front end to also allow sorting that list by birthday.

As the relevant template codes are only one line each, we will simply put them directly in the templateListener.xml file that will be shown later on. The code for the table head is similar to the other th elements:

1
<th class="columnDate columnBirthday{if $sortField == 'birthday'} active {@$sortOrder}{/if}"><a href="{link controller='PersonList'}pageNo={@$pageNo}&sortField=birthday&sortOrder={if $sortField == 'birthday' && $sortOrder == 'ASC'}DESC{else}ASC{/if}{/link}">{lang}wcf.person.birthday{/lang}</a></th>

For the table body’s column, we need to make sure that the birthday is only show if it is actually set:

1
<td class="columnDate columnBirthday">{if $person->birthday}{@$person->birthday|strtotime|date}{/if}</td>

Adding Birthday in Front End#

In the front end, we also want to make the list sortable by birthday and show the birthday as part of each person’s “statistics”.

To add the birthday as a valid sort field, we use BirthdaySortFieldPersonListPageListener just as in the ACP. In the front end, we will now use a template (__personListBirthdaySortField.tpl) instead of a directly putting the template code in the templateListener.xml file:

templates/__personListBirthdaySortField.tpl
1
<option value="birthday"{if $sortField == 'birthday'} selected{/if}>{lang}wcf.person.birthday{/lang}</option>

You might have noticed the two underscores at the beginning of the template file. For templates that are included via template listeners, this is the naming convention we use.

Putting the template code into a file has the advantage that in the administrator is able to edit the code directly via a custom template group, even though in this case this might not be very probable.

To show the birthday, we use the following template code for the personStatistics template event, which again makes sure that the birthday is only shown if it is actually set:

templates/__personListBirthday.tpl
1
2
3
4
{if $person->birthday}
    <dt>{lang}wcf.person.birthday{/lang}</dt>
    <dd>{@$person->birthday|strtotime|date}</dd>
{/if}

templateListener.xml#

The following code shows the templateListener.xml file used to install all mentioned template listeners:

templateListener.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0" encoding="UTF-8"?>
<data xmlns="http://www.woltlab.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.woltlab.com http://www.woltlab.com/tornado/5.4/templateListener.xsd">
    <import>
        <!-- admin -->
        <templatelistener name="personListBirthdayColumnHead">
            <eventname>columnHeads</eventname>
            <environment>admin</environment>
            <templatecode><![CDATA[<th class="columnDate columnBirthday{if $sortField == 'birthday'} active {@$sortOrder}{/if}"><a href="{link controller='PersonList'}pageNo={@$pageNo}&sortField=birthday&sortOrder={if $sortField == 'birthday' && $sortOrder == 'ASC'}DESC{else}ASC{/if}{/link}">{lang}wcf.person.birthday{/lang}</a></th>]]></templatecode>
            <templatename>personList</templatename>
        </templatelistener>
        <templatelistener name="personListBirthdayColumn">
            <eventname>columns</eventname>
            <environment>admin</environment>
            <templatecode><![CDATA[<td class="columnDate columnBirthday">{if $person->birthday}{@$person->birthday|strtotime|date}{/if}</td>]]></templatecode>
            <templatename>personList</templatename>
        </templatelistener>
        <!-- /admin -->

        <!-- user -->
        <templatelistener name="personListBirthday">
            <eventname>personStatistics</eventname>
            <environment>user</environment>
            <templatecode><![CDATA[{include file='__personListBirthday'}]]></templatecode>
            <templatename>personList</templatename>
        </templatelistener>
        <templatelistener name="personListBirthdaySortField">
            <eventname>sortField</eventname>
            <environment>user</environment>
            <templatecode><![CDATA[{include file='__personListBirthdaySortField'}]]></templatecode>
            <templatename>personList</templatename>
        </templatelistener>
        <!-- /user -->
    </import>
</data>

In cases where a template is used, we simply use the include syntax to load the template.

eventListener.xml#

There are two event listeners that make birthday a valid sort field in the ACP and the front end, respectively, and the third event listener takes care of setting the birthday.

eventListener.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version="1.0" encoding="UTF-8"?>
<data xmlns="http://www.woltlab.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.woltlab.com http://www.woltlab.com/XSD/5.4/eventListener.xsd">
    <import>
        <!-- admin -->
        <eventlistener name="validateSortField@wcf\acp\page\PersonListPage">
            <environment>admin</environment>
            <eventclassname>wcf\acp\page\PersonListPage</eventclassname>
            <eventname>validateSortField</eventname>
            <listenerclassname>wcf\system\event\listener\BirthdaySortFieldPersonListPageListener</listenerclassname>
        </eventlistener>
        <eventlistener name="createForm@wcf\acp\form\PersonAddForm">
            <environment>admin</environment>
            <eventclassname>wcf\acp\form\PersonAddForm</eventclassname>
            <eventname>createForm</eventname>
            <listenerclassname>wcf\system\event\listener\BirthdayPersonAddFormListener</listenerclassname>
            <inherit>1</inherit>
        </eventlistener>
        <!-- /admin -->

        <!-- user -->
        <eventlistener name="validateSortField@wcf\page\PersonListPage">
            <environment>user</environment>
            <eventclassname>wcf\page\PersonListPage</eventclassname>
            <eventname>validateSortField</eventname>
            <listenerclassname>wcf\system\event\listener\BirthdaySortFieldPersonListPageListener</listenerclassname>
        </eventlistener>
        <!-- /user -->
    </import>
</data>

package.xml#

The only relevant difference between the package.xml file of the base page from part 1 and the package.xml file of this package is that this package requires the base package com.woltlab.wcf.people (see <requiredpackages>):

package.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="UTF-8"?>
<package name="com.woltlab.wcf.people.birthday" xmlns="http://www.woltlab.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.woltlab.com http://www.woltlab.com/XSD/5.4/package.xsd">
    <packageinformation>
        <packagename>WoltLab Suite Core Tutorial: People (Birthday)</packagename>
        <packagedescription>Adds a birthday field to the people management system as part of a tutorial to create packages.</packagedescription>
        <version>5.4.0</version>
        <date>2021-04-16</date>
    </packageinformation>

    <authorinformation>
        <author>WoltLab GmbH</author>
        <authorurl>http://www.woltlab.com</authorurl>
    </authorinformation>

    <requiredpackages>
        <requiredpackage minversion="5.4.0 Alpha 1">com.woltlab.wcf</requiredpackage>
        <requiredpackage minversion="5.4.0">com.woltlab.wcf.people</requiredpackage>
    </requiredpackages>

    <excludedpackages>
        <excludedpackage version="6.0.0 Alpha 1">com.woltlab.wcf</excludedpackage>
    </excludedpackages>

    <instructions type="install">
        <instruction type="file" />
        <instruction type="database">acp/database/install_com.woltlab.wcf.people.birthday.php</instruction>
        <instruction type="template" />
        <instruction type="language" />

        <instruction type="eventListener" />
        <instruction type="templateListener" />
    </instructions>
</package>

This concludes the second part of our tutorial series after which you now have extended the base package using event listeners and template listeners that allow you to enter the birthday of the people.

The complete source code of this part can be found on GitHub.


Last update: 2021-04-23