Version 115.1 by Marius Dumitru Florea on 2020/05/18

Show last authors
1 {{box cssClass="floatinginfobox" title="**Contents**"}}
2 {{toc/}}
3 {{/box}}
4
5 This tutorial will show you how to build a Frequently Asked Questions (FAQs) [[Application>>platform:Features.Applications]] much like the one you can find on the [[FAQ page>>FAQ.WebHome]]. This is a very simple application that makes use of XWiki's [[classes, properties, and objects>>platform:DevGuide.DataModel||anchor="HXWikiClasses2CObjects2CandProperties"]]. It also uses a technique that you may frequently use as the basis for several different kinds of applications.
6
7 {{info}}
8 It's also possible to follow this tutorial as a [[video tutorial on Youtube>>https://youtu.be/upQWknV06D4]].
9 {{/info}}
10
11 = Prerequisites for following the tutorial =
12
13 {{warning}}
14 If you've already followed the [[AWM FAQ Tutorial>>Documentation.DevGuide.FAQTutorial.FAQTutorialAWM]] or installed the [[FAQ Application>>extensions:Extension.FAQ Application]] you'll need to do one of 2 things before you can take this tutorial:
15 * Delete the ##FAQ## space (if you've followed the AWM FAQ Tutorial) or uninstall the FAQ Application (if you've installed the FAQ Application)
16 * or simply follow the tutorial below but replace the space ##FAQ## with another value everywhere it's used. For example use ##MyFAQ## as the space name instead.
17 {{/warning}}
18
19 You should have [[installed XWiki>>platform:AdminGuide.Installation]] and have a [[basic understanding of how to use it>>platform:Features.WebHome]].
20
21 All through this tutorial you should refer to the [[XWiki Data Model>>platform:DevGuide.DataModel]] for information on XWiki's data model. You might also use the [[XWiki Scripting Guide>>platform:DevGuide.Scripting]] to get you started with scripting in XWiki and manipulating XWiki objects. In addition, this tutorial will introduce the concepts of Authoring Templates and Page Design Sheets, patterns that you will find particularly useful in creating XWiki applications. Completing this tutorial is a recommended prerequisite for anyone who wants to build custom applications on the XWiki engine.
22
23 {{warning}}
24 Make sure that your user is an [[Advanced user>>platform:Features.PageEditing||anchor="HAdvancedMode"]] before following this tutorial since you'll need for example to use the wiki editor (##Wiki > Edit## menu).
25 {{/warning}}
26
27 = Application Overview =
28
29 The FAQ application allows users to post a question by entering the question into a simple form field and then submitting the form. The question then appears in a list along with all other questions that have been previously posted. Users can click on the questions to view both the question and answer in a consistently styled view. If the question has not yet been answered, any user can post an answer to the question by editing the page. In edit mode, the page will display a web form that is the same for every FAQ page.
30
31 Let us begin by taking a look at what we are going to build. The new application will have the following views:
32
33 * The FAQ [[Class>>FAQ.WhatIsAClass]](((
34 {{image reference="FAQsSummary.png"/}}
35 )))
36
37 * An FAQ entry in View mode (notice that the properties can be edited in-place starting with XWiki 12.4RC1)(((
38 {{image reference="FAQSheetView.PNG"/}}
39 )))
40 * An FAQ entry in Edit mode(((
41 {{image reference="FAQSheetEdit.PNG"/}}
42 )))
43
44 = Authoring Templates and Page Design Sheets =
45
46 An Authoring Template is a template for creating documents of a specific type. Unlike a regular content page in edit mode with one field for freeform editing, an Authoring Template presents a custom set of form fields for creating a document with specific type of data. These form elements are defined by the properties of a class.
47
48 In object oriented programming, remember that a //class// is a template for an object. Using the analogy of a cookie cutter, the //class// is the //cookie cutter// and the //objects// are the actual //cookies//. An Authoring Template provides one way to represent a class visually so that users can fill out a form to set unique properties (values in form fields). When the user submits the form, they are creating a unique //object// of the //class// type.
49
50 Precisely, an Authoring Template is a prototype document used to create other specific instances of documents of the same type, along with a method of exposing the creation process to the user: the properties edit form. Remember that a XWiki Document can contain objects and this is the case of an authoring template: it is a XWiki Document with an empty object of a specific class, which is duplicated to create more and more documents based on that model, using the data inserted by the user in the editing form as specific values for the particular object instance in the current copy.
51
52 The Page Design Sheet is like a style sheet that defines what each document will look like when rendered. Even though the unique object instances will have different values for their properties, they will always have a consistent presentation display because they will be rendered through the Page Design Sheet. The XWiki API available in scripting languages provides a mechanism that will help us use the same sheet for both editing and view modes. We will see how we can achieve this once we get to the FAQ Design Sheet section.
53
54 = Go to the Class Editor Wizard =
55
56 Five pages, which collectively make up a [[XClass application>>extensions:Extension.XClass Application]] (a.k.a Class Wizard or Class Editor Wizard), have been developed to assist you in this process. Those page are technical pages hidden by default. To navigate to the wizard home page, go to your profile page, select the Preferences tab, edit the page and choose to view Hidden Documents. Enter a search query for the keyword "XWikiClasses". This should return a document called ##XWikiClasses## in the ##XWiki## space (i.e. ##XWiki.XWikiClasses##). (Note that the //title// of this document is "Data types".) This is the homepage of the class wizard creator: you are now ready to start building your FAQs application.
57
58 = Create the FAQ Class =
59
60 * On the Class Editor wizard entry page (XWiki.XWikiClasses), under the heading "Create a new data type", in the "Title" field, enter ##FAQ## as the name of the page to create:(((
61 {{image reference="CreateANewClass1.png"/}}
62 )))
63 * As you can see in the Breadcrumb below the new page will be created at location ##XWiki > FAQ##. In practice the Class Wizard will automatically prefix the page name with ##Class## (you could also enter ##FAQClass## as the page name directly).
64 * Now it would be nice to have it created in a new location such as ##FAQ > FAQ Class##. Since the ##FAQ## parent doesn't exist we cannot use the Tree picker button. Thus click the Pencil button as shown in the following image and replace ##XWiki## by ##FAQ##.(((
65 {{image reference="CreateANewClass2.png"/}}
66 )))
67 * In technical terms you're creating a page named ##FAQClass## (with a title of "FAQ Class") located in a space also called ##FAQ## and thus the technical reference is ##FAQ.FAQClass##.
68 * Click the "Create this Class" button. You should then see a page with the following content:(((
69 {{code language="none"}}
70 {{velocity}}
71 ## Replace the default space with the space where you want your documents to be created.
72 ## Replace the default parent with the one of your choice and save the document.
73 ##
74 #set($defaultSpace = $doc.space)
75 #set($defaultParent = $doc.fullName)
76 {{/velocity}}
77 {{/code}}
78 )))
79
80 In the code, change the word "$doc.space" with the name of the space where you want you FAQ pages to be created as the commented instructions in the page code suggest.
81 The line of code should look like this:
82
83 {{code language="none"}}
84 #set($defaultSpace = 'FAQ')
85 {{/code}}
86
87 You can also change the default parent of the new FAQ documents that are going to be created. To do so, replace the "$defaultParent" variable with the name of your document.
88 The line of code should look like this:
89
90 {{code language="none"}}
91 #set($defaultParent = 'FAQ.WebHome')
92 {{/code}}
93
94 Click the "Save & View" button. The class is now created and you should be looking at a page titled "Class: FAQ" that looks like this:
95
96 {{image reference="FAQClass1.PNG"/}}
97
98 = Add Properties to the Class =
99
100 Under the page title, you should see the words "The class does not have any properties yet. You can use the //__class editor__// to define them." Let's just follow those instructions!
101
102 * Click on the 'class editor' link
103 * Note that the link trail in the header is something like "Wiki Home / FAQ / FAQ Class". This shows you that you are indeed on the FAQ class page in Class edit mode.
104
105 In our document, we'll store both a //question// and an //answer//. So we need to create a property for each of them.
106
107 * Enter the text //question// in the "name" field
108 * Choose a TextArea type for the property and then click on "Add". The TextArea will ultimately give us a multi-line text field in our authoring template.(((
109 {{image reference="AddQuestionProperty.PNG"/}}
110 )))
111 * Click on the "+" icon to expand the options for the newly created property
112 * Change the value of the "Pretty Name" field to "Question"(capital Q):(((
113 {{image reference="QuestionProperty.PNG"/}}
114 )))
115 * Now create another property called //answer// the same way that you did for the previous "question" property (choose TextArea for the property type)
116 * Expand it from the property list and change the value of the "Pretty Name" field to "Answer"
117 * When you are done adding and configuring the properties, click the "Save & View" button
118
119 = Create the Page Design Sheet =
120
121 * After the previous step you are now on the FAQClass page which should look like this:(((
122 {{image reference="FAQClass2.PNG"/}}
123 )))
124 * Click the first button ("Create the document sheet") to create the document sheet (the Page Design Sheet). This sheet determines how your page's objects will be rendered to the user. The document is automatically created.
125 * You should see a warning message with the text "The sheet is not bound to the class so it won't be applied automatically when a page that has an object of this class is displayed". Click the "Bind the sheet to the class" link that appears after the text. **What this does is important**:
126 ** It adds an object of type ##XWiki.ClassSheetBinding## to the ##FAQ.FAQClass" document. Basically it ties the FAQ Class to the Sheet.##
127 ** **It's because of this object that users will be sent to form edition mode when editing FAQ entries**
128 * Now click on "View the sheet document". This takes you to the ##FAQ.FAQSheet## page which you can edit in wiki mode and see its default content:(((
129 {{code language="none"}}
130 {{velocity}}
131 ## You can modify this page to customize the presentation of your object.
132 ## At first you should keep the default presentation and just save the document.
133
134 #set($class = $doc.getObject('FAQ.FAQClass').xWikiClass)
135 #foreach($prop in $class.properties)
136 ; $prop.prettyName
137 : $doc.display($prop.getName())
138 #end
139 {{/velocity}}
140 {{/code}}
141 )))Let's take a moment now and analyze this code:(((
142 * The first line retrieves the ##FAQ.FAQClass## from the wiki
143 * Then we iterate through all its properties and display their values for the current document in a definition list.
144
145 As we mentioned, XWiki provides a mechanism that helps us create sheets used for both View and Edit mode.
146 This is the display function used in the line:
147
148 {{code language="none"}}
149 : $doc.display($prop.getName())
150 {{/code}}
151
152 It detects the current mode (Edit or View) and displays the property referenced by its argument as the mode dictates:
153
154 * In view mode it will display the value of the property
155 * In edit mode it will display a form field that will allow the user to edit it
156
157 This way we can use a single Design Sheet to both display and edit our FAQ entries. See the [[XWiki API reference>>platform:DevGuide.API]] and [[XWiki Scripting>>platform:DevGuide.Scripting]] pages for more details about this.
158
159 * Click "Save & View"
160 )))
161
162 = Create the Authoring Template =
163
164 * Navigate back to the ##FAQ.FAQClass## document (you can use the arrows in the breadcrumb to do so). The document should look like this:(((
165 {{image reference="FAQClass3.PNG"/}}
166 )))
167 * Click on the "Create the document template" button. The Authoring Template will be automatically created.
168
169 Note that earlier, we changed the space name preceding the page name because we wanted all of our FAQ pages to reside in a space named FAQ. Remember that all our documents will be copies of the Authoring Template used as a prototype so the content will be copied in all our FAQs documents and will execute the Design Sheet code in the context of the current document. See the [[dedicated page>>platform:DevGuide.IncludeInVelocity]] for more information regarding this technique.
170
171 Now we need to associate the prototype object with this document to turn it into a true authoring template:
172
173 * If you're on the template page, navigate back to the ##FAQ.FAQClass## document.
174 * At the bottom of the page, look for the following warning message: "The template does not contain an object of type FAQClass. Add a FAQ object to the template »."
175 * Click on "Add a FAQ object to the template »":(((
176 {{image reference="FAQObject.png"/}}
177 )))
178
179 Next, we want to remove the title for the newly created template:
180
181 * Navigate to the ##FAQ.FAQTemplate## document (you can click on the "View the template page (FAQ / FAQ Template)" link for doing that for example.
182 * Edit this document in Wiki mode
183 * Inside the Title field you have "FAQ Template" written -> delete this text
184 * Save & View
185
186 This step is needed so that all of our future entries don't have "FAQ Template" as their title.
187
188 Congratulations: you just created an Authoring Template! You're almost done now.
189
190 {{image reference="FAQClass4.PNG"/}}
191
192 = Create the Template Provider =
193
194 After the template was created and the object was added, a new section appears with a button to create a template provider to use the existing template.
195 The template provider is created with some default values, but those can be updated to match the needs.
196
197 {{gallery}}
198 image:3-missingTemplateProvider.png
199 image:4-addedTemplateProvider.png
200 image:5-templateProviderView.png
201 {{/gallery}}
202
203
204 = Create a home page for the FAQ application =
205
206 You want your users to be able to see a list of all existing questions and answers and to add new questions. The best way to do this is to put the FAQ application in its own space and to use that space's homepage to display existing questions.
207
208 Thus we now need to create the ##FAQ.WebHome## page
209
210 * Click on "FAQ" in the breadcrumb to navigate to ##FAQ.WebHome## and notice that the page doesn't exist.
211 * Edit it in wiki mode
212 * Type in the title "FAQs"
213
214 == Displaying existing FAQ entries ==
215
216 You have 2 options when it comes to displaying existing FAQ entries:
217
218 1. Use the livetable component
219 1. Write custom code in order to display them
220
221 === Using the Livetable component ===
222
223 In this section, we will show how to use the [[Livetable Macro>>extensions:Extension.Livetable Macro]] to display the existing questions and answers.
224
225 The livetable component will give users the ability to easily list and filter through existing FAQ documents. The macro is made of 3 parts:
226
227 * The list of columns: for each entry, we will display the question, the date when it was created and a special column that lets users quickly modify entries
228 * The properties of each column: for each column, we will define how it should be displayed, whether it should link to the entry and whether it should be filterable
229 * The livetable options: those are options related to the display of the livetable (in this case we will to display a tag cloud and 10 rows by default)
230
231 Here is the resulting code:
232
233 {{code language="none"}}
234 {{velocity}}
235 #set($columns = ["question", "doc.creationDate", "_actions"])
236 #set($columnsProperties = {
237 "question" : { "type" : "text", "link" : "view", "html" : "true", "sortable":true },
238 "_actions" : {"actions": ["edit","delete"]}
239 })
240 #set($options = {
241 "className":"FAQ.FAQClass",
242 "translationPrefix" : "faq.",
243 "tagCloud" : true,
244 "rowCount": 10
245 })
246 #livetable("faq" $columns $columnsProperties $options)
247 {{/velocity}}
248 {{/code}}
249
250 * Copy this code and paste it as Wiki content (inside ##FAQ.WebHome##)
251 * Click "Save and View"
252 * New FAQ entries will now be displayed on the page once you create them
253
254 The ##FAQ.WebHome## page should look similar to this:
255
256 {{image reference="FAQsLivetable.png"/}}
257
258 Notice how there are some translation keys displayed inside the livetable. Let's create a translations document and change those keys to actual text:
259
260 * Create a new page inside the FAQ space called Translations, i.e. at ##FAQ.Translations## (using the "+" button)
261 * Edit it in Wiki mode and paste this content inside:(((
262 {{code language="none"}}
263 faq.question=Question
264 faq.doc.creationDate=Creation Date
265 faq._actions=Actions
266 {{/code}}
267 )))
268 * Click "Save & View"
269 * Edit it again in Object mode and add a new ##XWiki.TranslationDocumentClass## object to mark the page as a page containing translations. Make sure to select the right scope. Using "Global" means the translations would be visible to all wikis (and it requires having Programming Rights!) and "Wiki" means it's visible to the current wiki only. Choose "Wiki" as the scope.
270 * Click "Save & View" again
271
272 Now the ##FAQ.WebHome## page should look like this (notice the translations instead of the keys):
273
274 {{image reference="FAQsLivetableWithTranslations.png"/}}
275
276 === Using custom code ===
277
278 You will need to write the following code:
279
280 * A XWQL query that will find all your FAQ documents. Check the [[Query API documentation>>extensions:Extension.Query Module]] to know more about it.
281 ** The XWQL query looks for all documents that have a ##FAQ.FAQClass## object other than the template
282 ** If no document has been created yet, a warning message is displayed
283 * A piece of velocity code to display all those documents
284 ** The velocity code loops in that list
285 ** For each item, the full document is loaded in memory so that values can be retrieved from it
286 ** For each document, the question is retrieved and displayed as a link towards the FAQ entry
287
288 Here is the resulting code:
289
290 {{code language="none"}}
291 = Existing FAQ entries =
292
293 {{velocity}}
294 #set($xwql = "from doc.object(FAQ.FAQClass) as faq where doc.fullName <> 'FAQ.FAQTemplate'")
295 #set($results = $services.query.xwql($xwql).execute())
296 #if($results.empty)
297 No FAQ has been created yet!
298 #else
299 #foreach ($item in $results)
300 #set($faq = $xwiki.getDocument($item))
301 * [[${faq.display("question").replace("<p>", "").replace("</p>", "")}>>${item}]]
302 #end
303 #end
304 {{/velocity}}
305 {{/code}}
306
307 * Copy this code and paste it as Wiki content inside ##FAQ.WebHome##
308 * Click "Save and View"
309 * New FAQ entries will now be displayed on the page once you create them
310
311 The ##FAQ.WebHome## page should look similar to this:
312
313 {{image reference="FAQsCustomCode.png"/}}
314
315 == Creating new FAQ entries ==
316
317 There are 2 ways for you to let your users create new FAQ entries:
318
319 1. Declare the FAQ as a template
320 1. Add a custom creation form
321
322 === Using a Template ===
323
324 You will have to define a template provider [[as explained on this page>>extensions:Extension.Administration Application||anchor="HCreatethetemplateprovider"]]
325
326 Go to your wiki's administration interface, in the "Templates" section (Administration -> Content -> Templates). Create a new template provider in the
327 ##FAQ## space and name it ##FAQTemplateProvider##
328
329 You can then use the following values:
330
331 * Provider name: ##FAQ Template Provider##
332 * Template name: ##New FAQ entry##
333 * Template to use: ##FAQ.FAQTemplate##
334
335 If you'd like, you can restrict FAQ entries so that they're created only in the ##FAQ## space. Once you're done, click "Save & View". Your template is now ready to be used! Users who click on the "Add >> Page" button will now have the option to create a new page using the FAQ template.
336
337 === Custom creation form ===
338
339 If you choose this option, you will need to write some code to let your users create new FAQ entries. To do this, you will have to create a form in which the user can enter the name of the questions she wants to create. Once typed in, the form calls the same page to trigger the new document creation based on the parameters entered by the user:
340
341 * The first part of the code checks whether the page has a parameter. If so:
342 ** The name of the document that will be created is computed
343 ** A check is done to verify the document doesn't exist yet
344 ** If everything's ok, the user is sent to the new document in inline edition mode
345 * The second part of the code is the actual FAQ creation form
346 ** It builds the name of the document to create it in the ##FAQ## space
347 ** It sets the document parent as being the current document
348 ** It defines the template to use to create the new document
349
350 {{code language="none"}}
351 {{velocity}}
352 #if("$!request.docName" != '')
353 ## Request for creating a new instance
354 #set($docName = ${request.docName})
355 #set($targetDocName = "${request.spaceName}.${docName}")
356 #if(!$xwiki.exists($targetDocName) && $xwiki.hasAccessLevel('edit', $xcontext.user, $targetDocName))
357 $response.sendRedirect($xwiki.getURL($targetDocName, 'inline', "template=${escapetool.url($request.template)}&parent=${escapetool.url($request.parent)}"))
358 ## Stop processing, since we already sent a redirect.
359 #stop
360 #end
361 #end
362
363 = Add a new question =
364
365 #if("$!targetDocName" != '' && $xwiki.exists($targetDocName))
366 {{warning}}The target document already exists. Please choose a different name, or [[view the existing document>>$targetDocName]]{{/warning}}
367 #elseif("$!targetDocName" != '')
368 {{warning}}You don't have permission to create that document{{/warning}}
369 #end
370
371 {{html}}
372 <form action="" id="newdoc" method="post">
373 <div>
374 <input type="hidden" name="parent" value="${doc.fullName}"/>
375 <input type="hidden" name="template" value="FAQ.FAQTemplate"/>
376 <input type="hidden" name="sheet" value="1"/>
377 <input type="hidden" name="spaceName" value="FAQ"/>
378 Document: <input type="text" name="docName" value="Enter your question here" class="withTip" size="50"/>
379 <span class="buttonwrapper"><input type="submit" value="Create this FAQ" class="button"/></span>
380 </div>
381 </form>
382 {{/html}}
383 {{/velocity}}
384 {{/code}}
385
386 * Copy this code and paste it as Wiki content inside ##FAQ.WebHome##, below the code that's already there
387 * Click "Save and View"
388 * A form to create new FAQ entries is now available on the page:(((
389 {{image reference="FAQsWithForm.png"/}}
390 )))
391
392 = Test the Application =
393
394 Now let's just create a new document in our application to test it out.
395
396 If you previously chose to use a "Custom creation form" for creating new FAQ entries, follow these steps:
397
398 * Go to ##FAQ.WebHome##
399 * Below the "Add a new question" header, enter a question (which will also be used as the document title) in the //Document// field
400 * Click //Create this FAQ//
401 * You can then enter your question in longer form using the //Question// field on the template, like this:(((
402 {{image reference="FAQSheetEdit.PNG"/}}
403 )))
404 * Click //Save & View// and then you will see the newly created document, like this:(((
405 {{image reference="FAQSheetView.PNG"/}}
406 )))
407 * Go back to the ##FAQ.WebHome## page (you can use the breadcrumbs) to see the list of existing questions(((
408 {{image reference="FAQsWithEntry.png"/}}
409 )))
410
411 = Conclusion =
412
413 This tutorial has taught you how to use the Class Wizard app and it has detailed the concepts of classes, objects and properties and introduced the authoring templates and page design sheets.
414
415 You may also have learned a little bit about Velocity scripting in documents. You can use these basic concepts to build custom applications at the document or presentation layer of XWiki without having to compile or deploy code.
416
417 As always, please take the time to make this document better for other users if you find ways that it can be improved as you read it for the first time.

Get Connected