Fix internal reference
[GitHub/WoltLab/woltlab.github.io.git] / docs / tutorial_tutorial-series_part-1-base-structure.md
1 # Tutorial Series Part 1: Base Structure
2
3 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.
4
5
6 ## Package Functionality
7
8 The package should provide the following possibilities/functions:
9
10 - Sortable list of all people in the ACP
11 - Ability to add, edit and delete people in the ACP
12 - Restrict the ability to add, edit and delete people (in short: manage people) in the ACP
13 - Sortable list of all people in the front end
14
15
16 ## Used Components
17
18 We will use the following package installation plugins:
19
20 - [acpTemplate package installation plugin](package_pip_acp-template.md),
21 - [acpMenu package installation plugin](package_pip_acp-menu.md),
22 - [file package installation plugin](package_pip_file.md),
23 - [language package installation plugin](package_pip_language.md),
24 - [menuItem package installation plugin](package_pip_menu-item.md),
25 - [page package installation plugin](package_pip_page.md),
26 - [sql package installation plugin](package_pip_sql.md),
27 - [template package installation plugin](package_pip_template.md),
28 - [userGroupOption package installation plugin](package_pip_user-group-option.md),
29
30 use [database objects](php_database-objects.md), create [pages](php_pages.md) and use [templates](view_templates.md).
31
32
33 ## Package Structure
34
35 The package will have the following file structure:
36
37 ```
38 ├── acpMenu.xml
39 ├── acptemplates
40 │ ├── personAdd.tpl
41 │ └── personList.tpl
42 ├── files
43 │ └── lib
44 │ ├── acp
45 │ │ ├── form
46 │ │ │ ├── PersonAddForm.class.php
47 │ │ │ └── PersonEditForm.class.php
48 │ │ └── page
49 │ │ └── PersonListPage.class.php
50 │ ├── data
51 │ │ └── person
52 │ │ ├── PersonAction.class.php
53 │ │ ├── Person.class.php
54 │ │ ├── PersonEditor.class.php
55 │ │ └── PersonList.class.php
56 │ └── page
57 │ └── PersonListPage.class.php
58 ├── install.sql
59 ├── language
60 │ ├── de.xml
61 │ └── en.xml
62 ├── menuItem.xml
63 ├── package.xml
64 ├── page.xml
65 ├── templates
66 │ └── personList.tpl
67 └── userGroupOption.xml
68 ```
69
70
71 ## Person Modeling
72
73 ### Database Table
74
75 As the first step, we have to model the people we want to manage with this package.
76 As this is only an introductory tutorial, we will keep things simple and only consider the first and last name of a person.
77 Thus, the database table we will store the people in only contains three columns:
78
79 1. `personID` is the unique numeric identifier of each person created,
80 1. `firstName` contains the first name of the person,
81 1. `lastName` contains the last name of the person.
82
83 The first file for our package is the `install.sql` file used to create such a database table during package installation:
84
85 ```sql
86 --8<-- "tutorial/tutorial-series/part-1/install.sql"
87 ```
88
89 ### Database Object
90
91 #### `Person`
92
93 In our PHP code, each person will be represented by an object of the following class:
94
95 ```php
96 --8<-- "tutorial/tutorial-series/part-1/files/lib/data/person/Person.class.php"
97 ```
98
99 The important thing here is that `Person` extends `DatabaseObject`.
100 Additionally, we implement the `IRouteController` interface, which allows us to use `Person` objects to create links, and we implement PHP's magic [__toString()](https://secure.php.net/manual/en/language.oop5.magic.php#object.tostring) method for convenience.
101
102 For every database object, you need to implement three additional classes:
103 an action class, an editor class and a list class.
104
105 #### `PersonAction`
106
107 ```php
108 --8<-- "tutorial/tutorial-series/part-1/files/lib/data/person/PersonAction.class.php"
109 ```
110
111 This implementation of `AbstractDatabaseObjectAction` is very basic and only sets the `$permissionsDelete` and `$requireACP` properties.
112 This is done so that later on, when implementing the people list for the ACP, we can delete people simply via AJAX.
113 `$permissionsDelete` has to be set to the permission needed in order to delete a person.
114 We will later use the [userGroupOption package installation plugin](package_pip_user-group-option.md) to create the `admin.content.canManagePeople` permission.
115 `$requireACP` restricts deletion of people to the ACP.
116
117 #### `PersonEditor`
118
119 ```php
120 --8<-- "tutorial/tutorial-series/part-1/files/lib/data/person/PersonEditor.class.php"
121 ```
122
123 This implementation of `DatabaseObjectEditor` fulfills the minimum requirement for a database object editor:
124 setting the static `$baseClass` property to the database object class name.
125
126 #### `PersonList`
127
128 ```php
129 --8<-- "tutorial/tutorial-series/part-1/files/lib/data/person/PersonList.class.php"
130 ```
131
132 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.
133
134
135 ## ACP
136
137 Next, we will take care of the controllers and views for the ACP.
138 In total, we need three each:
139
140 1. page to list people,
141 1. form to add people, and
142 1. form to edit people.
143
144 Before we create the controllers and views, let us first create the menu items for the pages in the ACP menu.
145
146 ### ACP Menu
147
148 We need to create three menu items:
149
150 1. a “parent” menu item on the second level of the ACP menu item tree,
151 1. a third level menu item for the people list page, and
152 1. a fourth level menu item for the form to add new people.
153
154 ```xml
155 --8<-- "tutorial/tutorial-series/part-1/acpMenu.xml"
156 ```
157
158 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.
159 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.
160
161 ### People List
162
163 To list the people in the ACP, we need a `PersonListPage` class and a `personList` template.
164
165 #### `PersonListPage`
166
167 ```php
168 --8<-- "tutorial/tutorial-series/part-1/files/lib/acp/page/PersonListPage.class.php"
169 ```
170
171 As WoltLab Suite Core already provides a powerful default implementation of a sortable page, our work here is minimal:
172
173 1. We need to set the active ACP menu item via the `$activeMenuItem`.
174 1. `$neededPermissions` contains a list of permissions of which the user needs to have at least one in order to see the person list.
175 We use the same permission for both the menu item and the page.
176 1. 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.
177 1. To validate the sort field passed with the request, we set `$validSortFields` to the available database table columns.
178
179 #### `personList.tpl`
180
181 ```smarty
182 --8<-- "tutorial/tutorial-series/part-1/acptemplates/personList.tpl"
183 ```
184
185 We will go piece by piece through the template code:
186
187 1. We include the `header` template and set the page title `wcf.acp.person.list`.
188 You have to include this template for every page!
189 1. We set the content header and additional provide a button to create a new person in the content header navigation.
190 1. 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.
191 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.
192 1. Now comes the main part of the page, the list of the people, which will only be displayed if any people exist.
193 Otherwise, an info box is displayed using the generic `wcf.global.noItems` language item.
194 The `$objects` template variable is automatically assigned by `wcf\page\MultipleLinkPage` and contains the `PersonList` object used to read the people from database.
195
196 The table itself consists of a `thead` and a `tbody` element and is extendable with more columns using the template events `columnHeads` and `columns`.
197 In general, every table should provide these events.
198 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.
199 The table can be sorted by clicking on the head of each column.
200 The used variables `$sortField` and `$sortOrder` are automatically assigned to the template by `SortablePage`.
201 1. The `.contentFooter` element is only shown if people exist as it basically repeats the `.contentHeaderNavigation` and `.paginationTop` element.
202 1. The JavaScript code here fulfills two duties:
203 Handling clicks on the delete icons and forwarding the requests via AJAX to the `PersonAction` class, and setting up some code that triggers if all people shown on the current page are deleted via JavaScript to either reload the page or show the `wcf.global.noItems` info box.
204 1. Lastly, the `footer` template is included that terminates the page.
205 You also have to include this template for every page!
206
207 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.
208
209 ### Person Add Form
210
211 Like the person list, the form to add new people requires a controller class and a template.
212
213 #### `PersonAddForm`
214
215 ```php
216 --8<-- "tutorial/tutorial-series/part-1/files/lib/acp/form/PersonAddForm.class.php"
217 ```
218
219 The properties here consist of two types:
220 the “housekeeping” properties `$activeMenuItem` and `$neededPermissions`, which fulfill the same roles as for `PersonListPage`, and the “data” properties `$firstName` and `$lastName`, which will contain the data entered by the user of the person to be created.
221
222 Now, let's go through each method in execution order:
223
224 1. `readFormParameters()` is called after the form has been submitted and reads the entered first and last name and sanitizes the values by calling `StringUtil::trim()`.
225 1. `validate()` is called after the form has been submitted and is used to validate the input data.
226 In case of invalid data, the method is expected to throw a `UserInputException`.
227 Here, the validation for first and last name is the same and quite basic:
228 We check that any name has been entered and that it is not longer than the database table column permits.
229 1. `save()` is called after the form has been submitted and the entered data has been validated and it creates the new person via `PersonAction`.
230 Please note that we do not just pass the first and last name to the action object but merge them with the `$this->additionalFields` array which can be used by event listeners of plugins to add additional data.
231 After creating the object, the `saved()` method is called which fires an event for plugins and the data properties are cleared so that the input fields on the page are empty so that another new person can be created.
232 Lastly, a `success` variable is assigned to the template which will show a message that the person has been successfully created.
233 1. `assignVariables()` assigns the values of the “data” properties to the template and additionally assigns an `action` variable.
234 This `action` variable will be used in the template to distinguish between adding a new person and editing an existing person so that which minimal adjustments, we can use the template for both cases.
235
236 #### `personAdd.tpl`
237
238 ```smarty
239 --8<-- "tutorial/tutorial-series/part-1/acptemplates/personAdd.tpl"
240 ```
241
242 We will now only concentrate on the new parts compared to `personList.tpl`:
243
244 1. We use the `$action` variable to distinguish between the languages items used for adding a person and for creating a person.
245 1. Including the `formError` template automatically shows an error message if the validation failed.
246 1. The `.success` element is shown after successful saving the data and, again, shows different a text depending on the executed action.
247 1. The main part is the `form` element which has a common structure you will find in many forms in WoltLab Suite Core.
248 The notable parts here are:
249 - The `action` attribute of the `form` element is set depending on which controller will handle the request.
250 In the link for the edit controller, we can now simply pass the edited `Person` object directly as the `Person` class implements the `IRouteController` interface.
251 - The field that caused the validation error can be accessed via `$errorField`.
252 - The type of the validation error can be accessed via `$errorType`.
253 For an empty input field, we show the generic `wcf.global.form.error.empty` language item.
254 In all other cases, we use the error type to determine the object- and property-specific language item to show.
255 The approach used here allows plugins to easily add further validation error messages by simply using a different error type and providing the associated language item.
256 - Input fields can be grouped into different `.section` elements.
257 At the end of each `.section` element, there should be an template event whose name ends with `Fields`.
258 The first part of the event name should reflect the type of fields in the particular `.section` element.
259 Here, the input fields are just general “data” fields so that the event is called `dataFields`.
260 - After the last `.section` element, fire a `section` event so that plugins can add further sections.
261 - Lastly, the `.formSubmit` shows the submit button and `{csrfToken}` contains a CSRF token that is automatically validated after the form is submitted.
262
263 ### Person Edit Form
264
265 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.
266
267 #### `PersonEditForm`
268
269 ```php
270 --8<-- "tutorial/tutorial-series/part-1/files/lib/acp/form/PersonEditForm.class.php"
271 ```
272
273 In general, edit forms extend the associated add form so that the code to read and to validate the input data is simply inherited.
274
275 After setting a different active menu item, we declare two new properties for the edited person:
276 the id of the person passed in the URL is stored in `$personID` and based on this ID, a `Person` object is created that is stored in the `$person` property.
277
278 Now let use go through the different methods in chronological order again:
279
280 1. `readParameters()` reads the passed ID of the edited person and creates a `Person` object based on this ID.
281 If the ID is invalid, `$this->person->personID` is `null` and an `IllegalLinkException` is thrown.
282 1. `readData()` only executes additional code in the case if `$_POST` is empty, thus only for the initial request before the form has been submitted.
283 The data properties of `PersonAddForm` are populated with the data of the edited person so that this data is shown in the form for the initial request.
284 1. `save()` handles saving the changed data.
285
286 !!! warning "Do not call `parent::save()` because that would cause `PersonAddForm::save()` to be executed and thus a new person would to be created! In order for the `save` event to be fired, call `AbstractForm::save()` instead!"
287
288 The only differences compared to `PersonAddForm::save()` are that we pass the edited object to the `PersonAction` constructor, execute the `update` action instead of the `create` action and do not clear the input fields after saving the changes.
289 1. In `assignVariables()`, we assign the edited `Person` object to the template, which is required to create the link in the form’s action property.
290 Furthermore, we assign the template variable `$action` `edit` as value.
291
292 !!! info "After calling `parent::assignVariables()`, the template variable `$action` actually has the value `add` so that here, we are overwriting this already assigned value."
293
294
295 ## Frontend
296
297 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.
298 This page should also be directly linked in the main menu.
299
300 ### `page.xml`
301
302 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](package_pip_page.md):
303
304 ```xml
305 --8<-- "tutorial/tutorial-series/part-1/page.xml"
306 ```
307
308 For more information about what each of the elements means, please refer to the [page package installation plugin page](package_pip_page.md).
309
310 ### `menuItem.xml`
311
312 Next, we register the menu item using the [menuItem package installation plugin](package_pip_menu-item.md):
313
314 ```xml
315 --8<-- "tutorial/tutorial-series/part-1/menuItem.xml"
316 ```
317
318 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.
319
320 ### People List
321
322 As in the ACP, we need a controller and a template.
323 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.
324 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.
325
326 #### `PersonListPage`
327
328 ```php
329 --8<-- "tutorial/tutorial-series/part-1/files/lib/page/PersonListPage.class.php"
330 ```
331
332 This class is almost identical to the ACP version.
333 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.
334 Furthermore, `$neededPermissions` has not been set because in the front end, users do not need any special permission to access the page.
335 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.
336
337 #### `personList.tpl`
338
339 ```smarty
340 --8<-- "tutorial/tutorial-series/part-1/templates/personList.tpl"
341 ```
342
343 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.
344 Furthermore, we include a template called `header` before actually showing any of the page contents and terminate the template by including the `footer` template.
345
346 Now, let us take a closer look at the differences:
347
348 - We do not explicitly create a `.contentHeader` element but simply assign the title to the `contentTitle` variable.
349 The value of the assignment is simply the title of the page and a badge showing the number of listed people.
350 The `header` template that we include later will handle correctly displaying the content header on its own based on the `$contentTitle` variable.
351 - Next, we create additional element for the HTML document’s `<head>` element.
352 In this case, we define the [canonical link of the page](https://en.wikipedia.org/wiki/Canonical_link_element) and, because we are showing paginated content, add links to the previous and next page (if they exist).
353 - 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.
354 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.
355 - The main part of the page is the listing of the people.
356 We use a structure similar to the one used for displaying registered users.
357 Here, for each person, we simply display a FontAwesome icon representing a person and show the person’s full name relying on `Person::__toString()`.
358 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.
359
360
361 ## `userGroupOption.xml`
362
363 We have already used the `admin.content.canManagePeople` permissions several times, now we need to install it using the [userGroupOption package installation plugin](package_pip_user-group-option.md):
364
365 ```xml
366 --8<-- "tutorial/tutorial-series/part-1/userGroupOption.xml"
367 ```
368
369 We use the existing `admin.content` user group option category for the permission as the people are “content” (similar the the ACP menu item).
370 As the permission is for administrators only, we set `defaultvalue` to `0` and `admindefaultvalue` to `1`.
371 This permission is only relevant for registered users so that it should not be visible when editing the guest user group.
372 This is achieved by setting `usersonly` to `1`.
373
374
375 ## `package.xml`
376
377 Lastly, we need to create the `package.xml` file.
378 For more information about this kind of file, please refer to [the `package.xml` page](package_package-xml.md).
379
380 ```xml
381 --8<-- "tutorial/tutorial-series/part-1/package.xml"
382 ```
383
384 As this is a package for WoltLab Suite Core 3, we need to require it using `<requiredpackage>`.
385 We require the latest version (when writing this tutorial) `3.0.0 RC 4`.
386 Additionally, we disallow installation of the package in the next major version `3.1` by excluding the `3.1.0 Alpha 1` version.
387 This ensures that if changes from WoltLab Suite Core 3.0 to 3.1 require changing some parts of the package, it will not break the instance in which the package is installed.
388
389 The most important part are to installation instructions.
390 First, we install the ACP templates, files and templates, create the database table and import the language item.
391 Afterwards, the ACP menu items and the permission are added.
392 Now comes the part of the instructions where the order of the instructions is crucial:
393 In `menuItem.xml`, we refer to the `com.woltlab.wcf.people.PersonList` page that is delivered by `page.xml`.
394 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!
395
396 ---
397
398 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.
399
400 The complete source code of this part can be found on [GitHub](https://github.com/WoltLab/woltlab.github.io/tree/master/_includes/tutorial/tutorial-series/part-1).