Skip to content

Tutorial Series Part 1: Base Structure#

In the first part of this tutorial series, we will lay out what the basic version of package should be able to do and how to implement these functions.

Package Functionality#

The package should provide the following possibilities/functions:

  • Sortable list of all people in the ACP
  • Ability to add, edit and delete people in the ACP
  • Restrict the ability to add, edit and delete people (in short: manage people) in the ACP
  • Sortable list of all people in the front end

Used Components#

We will use the following package installation plugins:

use database objects, create pages and use templates.

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
20
21
22
23
24
25
26
27
28
29
30
31
32
├── acpMenu.xml
├── acptemplates
│   ├── personAdd.tpl
│   └── personList.tpl
├── files
│   ├── acp
│   │   └── database
│   │       └── install_com.woltlab.wcf.people.php
│   └── lib
│       ├── acp
│       │   ├── form
│       │   │   ├── PersonAddForm.class.php
│       │   │   └── PersonEditForm.class.php
│       │   └── page
│       │       └── PersonListPage.class.php
│       ├── data
│       │   └── person
│       │       ├── Person.class.php
│       │       ├── PersonAction.class.php
│       │       ├── PersonEditor.class.php
│       │       └── PersonList.class.php
│       └── page
│           └── PersonListPage.class.php
├── language
│   ├── de.xml
│   └── en.xml
├── menuItem.xml
├── package.xml
├── page.xml
├── templates
│   └── personList.tpl
└── userGroupOption.xml

Person Modeling#

Database Table#

As the first step, we have to model the people we want to manage with this package. As this is only an introductory tutorial, we will keep things simple and only consider the first and last name of a person. Thus, the database table we will store the people in only contains three columns:

  1. personID is the unique numeric identifier of each person created,
  2. firstName contains the first name of the person,
  3. lastName contains the last name of the person.

The first file for our package is the install_com.woltlab.wcf.people.php file used to create such a database table during package installation:

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

use wcf\system\database\table\column\NotNullVarchar255DatabaseTableColumn;
use wcf\system\database\table\column\ObjectIdDatabaseTableColumn;
use wcf\system\database\table\DatabaseTable;

return [
    DatabaseTable::create('wcf1_person')
        ->columns([
            ObjectIdDatabaseTableColumn::create('personID'),
            NotNullVarchar255DatabaseTableColumn::create('firstName'),
            NotNullVarchar255DatabaseTableColumn::create('lastName'),
        ]),
];

Database Object#

Person#

In our PHP code, each person will be represented by an object of the following class:

files/lib/data/person/Person.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
35
36
37
38
39
<?php

namespace wcf\data\person;

use wcf\data\DatabaseObject;
use wcf\system\request\IRouteController;

/**
 * Represents a person.
 *
 * @author  Matthias Schmidt
 * @copyright   2001-2021 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\Data\Person
 *
 * @property-read   int     $personID   unique id of the person
 * @property-read   string  $firstName  first name of the person
 * @property-read   string  $lastName   last name of the person
 */
class Person extends DatabaseObject implements IRouteController
{
    /**
     * Returns the first and last name of the person if a person object is treated as a string.
     *
     * @return  string
     */
    public function __toString()
    {
        return $this->getTitle();
    }

    /**
     * @inheritDoc
     */
    public function getTitle()
    {
        return $this->firstName . ' ' . $this->lastName;
    }
}

The important thing here is that Person extends DatabaseObject. Additionally, we implement the IRouteController interface, which allows us to use Person objects to create links, and we implement PHP's magic __toString() method for convenience.

For every database object, you need to implement three additional classes: an action class, an editor class and a list class.

PersonAction#

files/lib/data/person/PersonAction.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
<?php

namespace wcf\data\person;

use wcf\data\AbstractDatabaseObjectAction;

/**
 * Executes person-related actions.
 *
 * @author  Matthias Schmidt
 * @copyright   2001-2021 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\Data\Person
 *
 * @method  Person      create()
 * @method  PersonEditor[]  getObjects()
 * @method  PersonEditor    getSingleObject()
 */
class PersonAction extends AbstractDatabaseObjectAction
{
    /**
     * @inheritDoc
     */
    protected $permissionsDelete = ['admin.content.canManagePeople'];

    /**
     * @inheritDoc
     */
    protected $requireACP = ['delete'];
}

This implementation of AbstractDatabaseObjectAction is very basic and only sets the $permissionsDelete and $requireACP properties. This is done so that later on, when implementing the people list for the ACP, we can delete people simply via AJAX. $permissionsDelete has to be set to the permission needed in order to delete a person. We will later use the userGroupOption package installation plugin to create the admin.content.canManagePeople permission. $requireACP restricts deletion of people to the ACP.

PersonEditor#

files/lib/data/person/PersonEditor.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
<?php

namespace wcf\data\person;

use wcf\data\DatabaseObjectEditor;

/**
 * Provides functions to edit 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\Data\Person
 *
 * @method static   Person  create(array $parameters = [])
 * @method      Person  getDecoratedObject()
 * @mixin       Person
 */
class PersonEditor extends DatabaseObjectEditor
{
    /**
     * @inheritDoc
     */
    protected static $baseClass = Person::class;
}

This implementation of DatabaseObjectEditor fulfills the minimum requirement for a database object editor: setting the static $baseClass property to the database object class name.

PersonList#

files/lib/data/person/PersonList.class.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php

namespace wcf\data\person;

use wcf\data\DatabaseObjectList;

/**
 * Represents a list of 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\Data\Person
 *
 * @method  Person      current()
 * @method  Person[]    getObjects()
 * @method  Person|null search($objectID)
 * @property    Person[]    $objects
 */
class PersonList extends DatabaseObjectList
{
}

Due to the default implementation of DatabaseObjectList, our PersonList class just needs to extend it and everything else is either automatically set by the code of DatabaseObjectList or, in the case of properties and methods, provided by that class.

ACP#

Next, we will take care of the controllers and views for the ACP. In total, we need three each:

  1. page to list people,
  2. form to add people, and
  3. form to edit people.

Before we create the controllers and views, let us first create the menu items for the pages in the ACP menu.

ACP Menu#

We need to create three menu items:

  1. a “parent” menu item on the second level of the ACP menu item tree,
  2. a third level menu item for the people list page, and
  3. a fourth level menu item for the form to add new people.
acpMenu.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?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/acpMenu.xsd">
    <import>
        <acpmenuitem name="wcf.acp.menu.link.person">
            <parent>wcf.acp.menu.link.content</parent>
        </acpmenuitem>
        <acpmenuitem name="wcf.acp.menu.link.person.list">
            <controller>wcf\acp\page\PersonListPage</controller>
            <parent>wcf.acp.menu.link.person</parent>
            <permissions>admin.content.canManagePeople</permissions>
        </acpmenuitem>
        <acpmenuitem name="wcf.acp.menu.link.person.add">
            <controller>wcf\acp\form\PersonAddForm</controller>
            <parent>wcf.acp.menu.link.person.list</parent>
            <permissions>admin.content.canManagePeople</permissions>
            <icon>fa-plus</icon>
        </acpmenuitem>
    </import>
</data>

We choose wcf.acp.menu.link.content as the parent menu item for the first menu item wcf.acp.menu.link.person because the people we are managing is just one form of content. The fourth level menu item wcf.acp.menu.link.person.add will only be shown as an icon and thus needs an additional element icon which takes a FontAwesome icon class as value.

People List#

To list the people in the ACP, we need a PersonListPage class and a personList template.

PersonListPage#

files/lib/data/person/PersonListPage.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
35
36
37
<?php

namespace wcf\acp\page;

use wcf\data\person\PersonList;
use wcf\page\SortablePage;

/**
 * Shows the list of 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\Acp\Page
 */
class PersonListPage extends SortablePage
{
    /**
     * @inheritDoc
     */
    public $activeMenuItem = 'wcf.acp.menu.link.person.list';

    /**
     * @inheritDoc
     */
    public $neededPermissions = ['admin.content.canManagePeople'];

    /**
     * @inheritDoc
     */
    public $objectListClassName = PersonList::class;

    /**
     * @inheritDoc
     */
    public $validSortFields = ['personID', 'firstName', 'lastName'];
}

As WoltLab Suite Core already provides a powerful default implementation of a sortable page, our work here is minimal:

  1. We need to set the active ACP menu item via the $activeMenuItem.
  2. $neededPermissions contains a list of permissions of which the user needs to have at least one in order to see the person list. We use the same permission for both the menu item and the page.
  3. The database object list class whose name is provided via $objectListClassName and that handles fetching the people from database is the PersonList class, which we have already created.
  4. To validate the sort field passed with the request, we set $validSortFields to the available database table columns.

personList.tpl#

acptemplates/personList.tpl
 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
{include file='header' pageTitle='wcf.acp.person.list'}

<header class="contentHeader">
    <div class="contentHeaderTitle">
        <h1 class="contentTitle">{lang}wcf.acp.person.list{/lang}</h1>
    </div>

    <nav class="contentHeaderNavigation">
        <ul>
            <li><a href="{link controller='PersonAdd'}{/link}" class="button"><span class="icon icon16 fa-plus"></span> <span>{lang}wcf.acp.menu.link.person.add{/lang}</span></a></li>

            {event name='contentHeaderNavigation'}
        </ul>
    </nav>
</header>

{hascontent}
    <div class="paginationTop">
        {content}{pages print=true assign=pagesLinks controller="PersonList" link="pageNo=%d&sortField=$sortField&sortOrder=$sortOrder"}{/content}
    </div>
{/hascontent}

{if $objects|count}
    <div class="section tabularBox">
        <table class="table jsObjectActionContainer" data-object-action-class-name="wcf\data\person\PersonAction">
            <thead>
                <tr>
                    <th class="columnID columnPersonID{if $sortField == 'personID'} active {@$sortOrder}{/if}" colspan="2"><a href="{link controller='PersonList'}pageNo={@$pageNo}&sortField=personID&sortOrder={if $sortField == 'personID' && $sortOrder == 'ASC'}DESC{else}ASC{/if}{/link}">{lang}wcf.global.objectID{/lang}</a></th>
                    <th class="columnTitle columnFirstName{if $sortField == 'firstName'} active {@$sortOrder}{/if}"><a href="{link controller='PersonList'}pageNo={@$pageNo}&sortField=firstName&sortOrder={if $sortField == 'firstName' && $sortOrder == 'ASC'}DESC{else}ASC{/if}{/link}">{lang}wcf.person.firstName{/lang}</a></th>
                    <th class="columnTitle columnLastName{if $sortField == 'lastName'} active {@$sortOrder}{/if}"><a href="{link controller='PersonList'}pageNo={@$pageNo}&sortField=lastName&sortOrder={if $sortField == 'lastName' && $sortOrder == 'ASC'}DESC{else}ASC{/if}{/link}">{lang}wcf.person.lastName{/lang}</a></th>

                    {event name='columnHeads'}
                </tr>
            </thead>

            <tbody class="jsReloadPageWhenEmpty">
                {foreach from=$objects item=person}
                    <tr class="jsObjectActionObject" data-object-id="{@$person->getObjectID()}">
                        <td class="columnIcon">
                            <a href="{link controller='PersonEdit' object=$person}{/link}" title="{lang}wcf.global.button.edit{/lang}" class="jsTooltip"><span class="icon icon16 fa-pencil"></span></a>
                            {objectAction action="delete" objectTitle=$person->getTitle()}

                            {event name='rowButtons'}
                        </td>
                        <td class="columnID">{#$person->personID}</td>
                        <td class="columnTitle columnFirstName"><a href="{link controller='PersonEdit' object=$person}{/link}">{$person->firstName}</a></td>
                        <td class="columnTitle columnLastName"><a href="{link controller='PersonEdit' object=$person}{/link}">{$person->lastName}</a></td>

                        {event name='columns'}
                    </tr>
                {/foreach}
            </tbody>
        </table>
    </div>

    <footer class="contentFooter">
        {hascontent}
            <div class="paginationBottom">
                {content}{@$pagesLinks}{/content}
            </div>
        {/hascontent}

        <nav class="contentFooterNavigation">
            <ul>
                <li><a href="{link controller='PersonAdd'}{/link}" class="button"><span class="icon icon16 fa-plus"></span> <span>{lang}wcf.acp.menu.link.person.add{/lang}</span></a></li>

                {event name='contentFooterNavigation'}
            </ul>
        </nav>
    </footer>
{else}
    <p class="info">{lang}wcf.global.noItems{/lang}</p>
{/if}

{include file='footer'}

We will go piece by piece through the template code:

  1. We include the header template and set the page title wcf.acp.person.list. You have to include this template for every page!
  2. We set the content header and additional provide a button to create a new person in the content header navigation.
  3. As not all people are listed on the same page if many people have been created, we need a pagination for which we use the pages template plugin. The {hascontent}{content}{/content}{/hascontent} construct ensures the .paginationTop element is only shown if the pages template plugin has a return value, thus if a pagination is necessary.
  4. Now comes the main part of the page, the list of the people, which will only be displayed if any people exist. Otherwise, an info box is displayed using the generic wcf.global.noItems language item. The $objects template variable is automatically assigned by wcf\page\MultipleLinkPage and contains the PersonList object used to read the people from database. The table itself consists of a thead and a tbody element and is extendable with more columns using the template events columnHeads and columns. In general, every table should provide these events. The default structure of a table is used here so that the first column of the content rows contains icons to edit and to delete the row (and provides another standard event rowButtons) and that the second column contains the ID of the person. The table can be sorted by clicking on the head of each column. The used variables $sortField and $sortOrder are automatically assigned to the template by SortablePage.
  5. The .contentFooter element is only shown if people exist as it basically repeats the .contentHeaderNavigation and .paginationTop element.
  6. The delete button for each person shown in the .columnIcon element relies on the global WoltLabSuite/Core/Ui/Object/Action module which only requires the jsObjectActionContainer CSS class in combination with the data-object-action-class-name attribute for the table element, the jsObjectActionObject CSS class for each person's tr element in combination with the data-object-id attribute, and lastly the delete button itself, which is created with the objectAction template plugin.
  7. The .jsReloadPageWhenEmpty CSS class on the tbody element ensures that once all persons on the page have been deleted, the page is reloaded.
  8. Lastly, the footer template is included that terminates the page. You also have to include this template for every page!

Now, we have finished the page to manage the people so that we can move on to the forms with which we actually create and edit the people.

Person Add Form#

Like the person list, the form to add new people requires a controller class and a template.

PersonAddForm#

files/lib/acp/form/PersonAddForm.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php

namespace wcf\acp\form;

use wcf\data\person\PersonAction;
use wcf\form\AbstractFormBuilderForm;
use wcf\system\form\builder\container\FormContainer;
use wcf\system\form\builder\field\TextFormField;

/**
 * Shows the form to create a new person.
 *
 * @author  Matthias Schmidt
 * @copyright   2001-2021 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\Acp\Form
 */
class PersonAddForm extends AbstractFormBuilderForm
{
    /**
     * @inheritDoc
     */
    public $activeMenuItem = 'wcf.acp.menu.link.person.add';

    /**
     * @inheritDoc
     */
    public $formAction = 'create';

    /**
     * @inheritDoc
     */
    public $neededPermissions = ['admin.content.canManagePeople'];

    /**
     * @inheritDoc
     */
    public $objectActionClass = PersonAction::class;

    /**
     * @inheritDoc
     */
    public $objectEditLinkController = PersonEditForm::class;

    /**
     * @inheritDoc
     */
    protected function createForm()
    {
        parent::createForm();

        $this->form->appendChild(
            FormContainer::create('data')
                ->label('wcf.global.form.data')
                ->appendChildren([
                    TextFormField::create('firstName')
                        ->label('wcf.person.firstName')
                        ->required()
                        ->autoFocus()
                        ->maximumLength(255),

                    TextFormField::create('lastName')
                        ->label('wcf.person.lastName')
                        ->required()
                        ->maximumLength(255),
                ])
        );
    }
}

The properties here consist of three types: the “housekeeping” properties $activeMenuItem and $neededPermissions, which fulfill the same roles as for PersonListPage, and the $objectEditLinkController property, which is used to generate a link to edit the newly created person after submitting the form, and finally $formAction and $objectActionClass required by the PHP form builder API used to generate the form.

Because of using form builder, we only have to set up the two form fields for entering the first and last name, respectively:

  1. Each field is a simple single-line text field, thus we use TextFormField.
  2. The parameter of the create() method expects the id of the field/name of the database object property, which is firstName and lastName, respectively, here.
  3. The language item of the label shown in the ouput above the input field is set via the label() method.
  4. As both fields have to be filled out, required() is called, and the maximum length is set via maximumLength().
  5. Lastly, to make it easier to fill out the form more quickly, the first field is auto-focused by calling autoFocus().

personAdd.tpl#

acptemplates/personAdd.tpl
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
{include file='header' pageTitle='wcf.acp.person.'|concat:$action}

<header class="contentHeader">
    <div class="contentHeaderTitle">
        <h1 class="contentTitle">{lang}wcf.acp.person.{$action}{/lang}</h1>
    </div>

    <nav class="contentHeaderNavigation">
        <ul>
            <li><a href="{link controller='PersonList'}{/link}" class="button"><span class="icon icon16 fa-list"></span> <span>{lang}wcf.acp.menu.link.person.list{/lang}</span></a></li>

            {event name='contentHeaderNavigation'}
        </ul>
    </nav>
</header>

{@$form->getHtml()}

{include file='footer'}

We will now only concentrate on the new parts compared to personList.tpl:

  1. We use the $action variable to distinguish between the languages items used for adding a person and for creating a person.
  2. Because of form builder, we only have to call {@$form->getHtml()} to generate all relevant output for the form.

Person Edit Form#

As mentioned before, for the form to edit existing people, we only need a new controller as the template has already been implemented in a way that it handles both, adding and editing.

PersonEditForm#

files/lib/acp/form/PersonEditForm.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
35
36
37
38
39
40
41
42
43
<?php

namespace wcf\acp\form;

use wcf\data\person\Person;
use wcf\system\exception\IllegalLinkException;

/**
 * Shows the form to edit an existing person.
 *
 * @author  Matthias Schmidt
 * @copyright   2001-2021 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\Acp\Form
 */
class PersonEditForm extends PersonAddForm
{
    /**
     * @inheritDoc
     */
    public $activeMenuItem = 'wcf.acp.menu.link.person';

    /**
     * @inheritDoc
     */
    public $formAction = 'update';

    /**
     * @inheritDoc
     */
    public function readParameters()
    {
        parent::readParameters();

        if (isset($_REQUEST['id'])) {
            $this->formObject = new Person($_REQUEST['id']);

            if (!$this->formObject->getObjectID()) {
                throw new IllegalLinkException();
            }
        }
    }
}

In general, edit forms extend the associated add form so that the code to read and to validate the input data is simply inherited.

After setting a different active menu item, we have to change the value of $formAction because this form, in contrast to PersonAddForm, does not create but update existing persons.

As we rely on form builder, the only thing necessary in this controller is to read and validate the edit object, i.e. the edited person, which is done in readParameters().

Frontend#

For the front end, that means the part with which the visitors of a website interact, we want to implement a simple sortable page that lists the people. This page should also be directly linked in the main menu.

page.xml#

First, let us register the page with the system because every front end page or form needs to be explicitly registered using the page package installation plugin:

page.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?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/page.xsd">
    <import>
        <page identifier="com.woltlab.wcf.people.PersonList">
            <pageType>system</pageType>
            <controller>wcf\page\PersonListPage</controller>
            <name language="de">Personen-Liste</name>
            <name language="en">Person List</name>

            <content language="de">
                <title>Personen</title>
            </content>
            <content language="en">
                <title>People</title>
            </content>
        </page>
    </import>
</data>

For more information about what each of the elements means, please refer to the page package installation plugin page.

Next, we register the menu item using the menuItem package installation plugin:

menuItem.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?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/menuItem.xsd">
    <import>
        <item identifier="com.woltlab.wcf.people.PersonList">
            <menu>com.woltlab.wcf.MainMenu</menu>
            <title language="de">Personen</title>
            <title language="en">People</title>
            <page>com.woltlab.wcf.people.PersonList</page>
        </item>
    </import>
</data>

Here, the import parts are that we register the menu item for the main menu com.woltlab.wcf.MainMenu and link the menu item with the page com.woltlab.wcf.people.PersonList, which we just registered.

People List#

As in the ACP, we need a controller and a template. You might notice that both the controller’s (unqualified) class name and the template name are the same for the ACP and the front end. This is no problem because the qualified names of the classes differ and the files are stored in different directories and because the templates are installed by different package installation plugins and are also stored in different directories.

PersonListPage#

files/lib/page/PersonListPage.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
<?php

namespace wcf\page;

use wcf\data\person\PersonList;

/**
 * Shows the list of 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\Page
 */
class PersonListPage extends SortablePage
{
    /**
     * @inheritDoc
     */
    public $defaultSortField = 'lastName';

    /**
     * @inheritDoc
     */
    public $objectListClassName = PersonList::class;

    /**
     * @inheritDoc
     */
    public $validSortFields = ['personID', 'firstName', 'lastName'];
}

This class is almost identical to the ACP version. In the front end, we do not need to set the active menu item manually because the system determines the active menu item automatically based on the requested page. Furthermore, $neededPermissions has not been set because in the front end, users do not need any special permission to access the page. In the front end, we explicitly set the $defaultSortField so that the people listed on the page are sorted by their last name (in ascending order) by default.

personList.tpl#

templates/personList.tpl
  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
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
{capture assign='contentTitle'}{lang}wcf.person.list{/lang} <span class="badge">{#$items}</span>{/capture}

{capture assign='headContent'}
    {if $pageNo < $pages}
        <link rel="next" href="{link controller='PersonList'}pageNo={@$pageNo+1}{/link}">
    {/if}
    {if $pageNo > 1}
        <link rel="prev" href="{link controller='PersonList'}{if $pageNo > 2}pageNo={@$pageNo-1}{/if}{/link}">
    {/if}
    <link rel="canonical" href="{link controller='PersonList'}{if $pageNo > 1}pageNo={@$pageNo}{/if}{/link}">
{/capture}

{capture assign='sidebarRight'}
    <section class="box">
        <form method="post" action="{link controller='PersonList'}{/link}">
            <h2 class="boxTitle">{lang}wcf.global.sorting{/lang}</h2>

            <div class="boxContent">
                <dl>
                    <dt></dt>
                    <dd>
                        <select id="sortField" name="sortField">
                            <option value="firstName"{if $sortField == 'firstName'} selected{/if}>{lang}wcf.person.firstName{/lang}</option>
                            <option value="lastName"{if $sortField == 'lastName'} selected{/if}>{lang}wcf.person.lastName{/lang}</option>
                            {event name='sortField'}
                        </select>
                        <select name="sortOrder">
                            <option value="ASC"{if $sortOrder == 'ASC'} selected{/if}>{lang}wcf.global.sortOrder.ascending{/lang}</option>
                            <option value="DESC"{if $sortOrder == 'DESC'} selected{/if}>{lang}wcf.global.sortOrder.descending{/lang}</option>
                        </select>
                    </dd>
                </dl>

                <div class="formSubmit">
                    <input type="submit" value="{lang}wcf.global.button.submit{/lang}" accesskey="s">
                </div>
            </div>
        </form>
    </section>
{/capture}

{include file='header'}

{hascontent}
    <div class="paginationTop">
        {content}
            {pages print=true assign=pagesLinks controller='PersonList' link="pageNo=%d&sortField=$sortField&sortOrder=$sortOrder"}
        {/content}
    </div>
{/hascontent}

{if $items}
    <div class="section sectionContainerList">
        <ol class="containerList personList">
            {foreach from=$objects item=person}
                <li>
                    <div class="box48">
                        <span class="icon icon48 fa-user"></span>

                        <div class="details personInformation">
                            <div class="containerHeadline">
                                <h3>{$person}</h3>
                            </div>

                            {hascontent}
                                <ul class="inlineList commaSeparated">
                                    {content}{event name='personData'}{/content}
                                </ul>
                            {/hascontent}

                            {hascontent}
                                <dl class="plain inlineDataList small">
                                    {content}{event name='personStatistics'}{/content}
                                </dl>
                            {/hascontent}
                        </div>
                    </div>
                </li>
            {/foreach}
        </ol>
    </div>
{else}
    <p class="info">{lang}wcf.global.noItems{/lang}</p>
{/if}

<footer class="contentFooter">
    {hascontent}
        <div class="paginationBottom">
            {content}{@$pagesLinks}{/content}
        </div>
    {/hascontent}

    {hascontent}
        <nav class="contentFooterNavigation">
            <ul>
                {content}{event name='contentFooterNavigation'}{/content}
            </ul>
        </nav>
    {/hascontent}
</footer>

{include file='footer'}

If you compare this template to the one used in the ACP, you will recognize similar elements like the .paginationTop element, the p.info element if no people exist, and the .contentFooter element. Furthermore, we include a template called header before actually showing any of the page contents and terminate the template by including the footer template.

Now, let us take a closer look at the differences:

  • We do not explicitly create a .contentHeader element but simply assign the title to the contentTitle variable. The value of the assignment is simply the title of the page and a badge showing the number of listed people. The header template that we include later will handle correctly displaying the content header on its own based on the $contentTitle variable.
  • Next, we create additional element for the HTML document’s <head> element. In this case, we define the canonical link of the page and, because we are showing paginated content, add links to the previous and next page (if they exist).
  • We want the page to be sortable but as we will not be using a table for listing the people like in the ACP, we are not able to place links to sort the people into the table head. Instead, usually a box is created in the sidebar on the right-hand side that contains select elements to determine sort field and sort order.
  • The main part of the page is the listing of the people. We use a structure similar to the one used for displaying registered users. Here, for each person, we simply display a FontAwesome icon representing a person and show the person’s full name relying on Person::__toString(). Additionally, like in the user list, we provide the initially empty ul.inlineList.commaSeparated and dl.plain.inlineDataList.small elements that can be filled by plugins using the templates events.

userGroupOption.xml#

We have already used the admin.content.canManagePeople permissions several times, now we need to install it using the userGroupOption package installation plugin:

userGroupOption.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<?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/userGroupOption.xsd">
    <import>
        <options>
            <option name="admin.content.canManagePeople">
                <categoryname>admin.content</categoryname>
                <optiontype>boolean</optiontype>
                <defaultvalue>0</defaultvalue>
                <admindefaultvalue>1</admindefaultvalue>
                <usersonly>1</usersonly>
            </option>
        </options>
    </import>
</data>

We use the existing admin.content user group option category for the permission as the people are “content” (similar the the ACP menu item). As the permission is for administrators only, we set defaultvalue to 0 and admindefaultvalue to 1. This permission is only relevant for registered users so that it should not be visible when editing the guest user group. This is achieved by setting usersonly to 1.

package.xml#

Lastly, we need to create the package.xml file. For more information about this kind of file, please refer to the package.xml page.

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
34
35
<?xml version="1.0" encoding="UTF-8"?>
<package name="com.woltlab.wcf.people" 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</packagename>
        <packagedescription>Adds a simple management system for people 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>
    </requiredpackages>

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

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

        <instruction type="acpMenu" />
        <instruction type="page" />
        <instruction type="menuItem" />
        <instruction type="userGroupOption" />
    </instructions>
</package>

As this is a package for WoltLab Suite Core 3, we need to require it using <requiredpackage>. We require the latest version (when writing this tutorial) 5.4.0 Alpha 1. Additionally, we disallow installation of the package in the next major version 6.0 by excluding the 6.0.0 Alpha 1 version.

The most important part are to installation instructions. First, we install the ACP templates, files and templates, create the database table and import the language item. Afterwards, the ACP menu items and the permission are added. Now comes the part of the instructions where the order of the instructions is crucial: In menuItem.xml, we refer to the com.woltlab.wcf.people.PersonList page that is delivered by page.xml. As the menu item package installation plugin validates the given page and throws an exception if the page does not exist, we need to install the page before the menu item!


This concludes the first part of our tutorial series after which you now have a working simple package with which you can manage people in the ACP and show the visitors of your website a simple list of all created people in the front end.

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


Last update: 2021-04-23