Wiki source code of Creating a FAQ Application

Version 92.8 by Vincent Massol on 2017/01/17

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>>xwiki: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 = Prerequisites for following the tutorial =
8
9 You should have [[installed XWiki>>AdminGuide.Installation]] and have a [[basic understanding of how to use it>>Features.WebHome]].
10
11 All through this tutorial you should refer to the [[XWiki Data Model>>DevGuide.DataModel]] for information on XWiki's data model. You might also use the [[XWiki Scripting Guide>>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.
12
13 = Application Overview =
14
15 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.
16
17 Let us begin by taking a look at what we are going to build. The new application will have the following views:
18
19 * The FAQ [[Class>>xwiki:FAQ.WhatIsAClass]]
20 {{image reference="FAQsSummary.png"/}}
21 * An FAQ entry in View mode
22 {{image reference="FAQSheetView.PNG"/}}
23 * An FAQ entry in Edit mode
24 {{image reference="FAQSheetEdit.PNG"/}}
25
26 = Authoring Templates and Page Design Sheets =
27
28 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.
29
30 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.
31
32 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.
33
34 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.
35
36 = Go to the Class Editor Wizard =
37
38 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##). This is the homepage of the class wizard creator: you are now ready to start building your FAQs application.
39
40 = Create the FAQ Class =
41
42 * 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:(((
43 {{image reference="CreateANewClass1.png"/}}
44 )))
45 * As you can see in the Breadcrumb below the new page will be created at location ##XWiki > FAQ##. Now it would be nice to have it created in a new location such as ##FAQ > FAQ##. 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##:(((
46 {{image reference="CreateANewClass2.png"/}}
47 )))
48 * In technical terms you're creating a page named ##FAQ## located in a space also called ##FAQ## and the reference is ##FAQ.FAQ##.
49 * Click the "Create this Class" button. You should then see a page with the following content:(((
50 {{code language="none"}}
51 {{velocity}}
52 ## Replace the default space with the space where you want your documents to be created.
53 ## Replace the default parent with the one of your choice and save the document.
54 ##
55 #set($defaultSpace = $doc.space)
56 #set($defaultParent = $doc.fullName)
57 {{/velocity}}
58 {{/code}}
59 )))
60
61 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.
62 The line of code should look like this:
63
64 {{code language="none"}}
65 #set($defaultSpace = 'FAQ')
66 {{/code}}
67
68 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.
69 The line of code should look like this:
70
71 {{code language="none"}}
72 #set($defaultParent = 'FAQ.WebHome')
73 {{/code}}
74
75 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:
76
77 {{image reference="FAQClass1.PNG"/}}
78
79 = Add Properties to the Class =
80
81 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!
82
83 * Click on the 'class editor' link
84 * 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.
85
86 In our document, we'll store both a //question// and an //answer//. So we need to create a property for each of them.
87
88 * Enter the text //question// in the "name" field
89 * 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.(((
90 {{image reference="AddQuestionProperty.PNG"/}}
91 )))
92 * Click on the "+" icon to expand the options for the newly created property
93 * Change the value of the "Pretty Name" field to "Question"(capital Q):(((
94 {{image reference="QuestionProperty.PNG"/}}
95 )))
96 * Now create another property called //answer// the same way that you did for the previous "question" property (choose TextArea for the property type)
97 * Expand it from the property list and change the value of the "Pretty Name" field to "Answer"
98 * When you are done adding and configuring the properties, click the "Save & View" button
99
100 = Create the Page Design Sheet =
101
102 * After the previous step you are now on the FAQClass page which should look like this:(((
103 {{image reference="FAQClass2.PNG"/}}
104 )))
105 * 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.
106 * 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**:
107 ** It adds an object of type ##XWiki.ClassSheetBinding## to the ##FAQ.FAQClass" document. Basically it ties the FAQ Class to the Sheet.
108 ** **It's because of this object that users will be sent to form edition mode when editing FAQ entries**
109 * 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:(((
110 {{code language="none"}}
111 {{velocity}}
112 ## You can modify this page to customize the presentation of your object.
113 ## At first you should keep the default presentation and just save the document.
114
115 #set($class = $doc.getObject('FAQ.FAQClass').xWikiClass)
116 #foreach($prop in $class.properties)
117 ; $prop.prettyName
118 : $doc.display($prop.getName())
119 #end
120 {{/velocity}}
121 {{/code}}
122 )))Let's take a moment now and analyze this code:(((
123
124 * The first line retrieves the ##FAQ.FAQClass## from the wiki
125 * Then we iterate through all its properties and display their values for the current document in a definition list.
126
127 As we mentioned, XWiki provides a mechanism that helps us create sheets used for both View and Edit mode.
128 This is the display function used in the line:
129
130 {{code language="none"}}
131 : $doc.display($prop.getName())
132 {{/code}}
133
134 It detects the current mode (Edit or View) and displays the property referenced by its argument as the mode dictates:
135
136 * In view mode it will display the value of the property
137 * In edit mode it will display a form field that will allow the user to edit it
138
139 This way we can use a single Design Sheet to both display and edit our FAQ entries. See the [[XWiki API reference>>DevGuide.API]] and [[XWiki Scripting>>DevGuide.Scripting]] pages for more details about this.
140
141 * Click "Save & View"
142 )))
143
144 = Create the Authoring Template =
145
146 * Navigate back to the ##FAQ.FAQClass## document (you can use the arrows in the breadcrumb to do so). The document should look like this:(((
147 {{image reference="FAQClass3.PNG"/}}
148 )))
149 * Click on the "Create the document template" button. The Authoring Template will be automatically created.
150
151 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>>DevGuide.IncludeInVelocity]] for more information regarding this technique.
152
153 Now we need to associate the prototype object with this document to turn it into a true authoring template:
154
155 * If you're on the template page, navigate back to the ##FAQ.FAQClass## document.
156 * 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 »."
157 * Click on "Add a FAQ object to the template »":(((
158 {{image reference="FAQObject.png"/}}
159 )))
160
161 Next, we want to remove the title for the newly created template:
162
163 * Navigate to the ##FAQ.FAQTemplate## document (you can click on the "View the template page (FAQ / FAQ Template)" link for doing that for example.
164 * Edit this document in Wiki mode
165 * Inside the Title field you have "FAQ Template" written -> delete this text
166 * Save & View
167
168 This step is needed so that all of our future entries don't have "FAQ Template" as their title.
169
170 Congratulations: you just created an Authoring Template! You're almost done now.
171
172 {{image reference="FAQClass4.PNG"/}}
173
174 = Create a home page for the FAQ application =
175
176 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.
177 We need to create the FAQ.WebHome page
178
179 * Click on "FAQClass" in the breadcrumb
180 * Click on the "+ Add" green button
181 * Choose FAQ as the "Space name" and type WebHome for the "Page name" field
182 * Click "Create"
183 * Type in the title "FAQs" in the title field
184 * Click "Save & View"
185
186 == Displaying existing FAQ entries ==
187
188 You have 2 options when it comes to displaying existing FAQ entries:
189
190 1. Use the livetable component
191 1. Write custom code in order to display them
192
193 === Using the Livetable component ===
194
195 In this section, we will show how to use the [[Livetable Macro>>extensions:Extension.Livetable Macro]] to display the existing questions and answers.
196
197 The livetable component will give users the ability to easily list and filter through existing FAQ documents. The macro is made of 3 parts:
198
199 * 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
200 * 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
201 * 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)
202
203 Here is the resulting code:
204
205 {{code language="none"}}
206 {{velocity}}
207 #set($columns = ["question", "doc.creationDate", "_actions"])
208 #set($columnsProperties = {
209 "question" : { "type" : "text", "link" : "view", "html" : "true", "sortable":true },
210 "_actions" : {"actions": ["edit","delete"]}
211 })
212 #set($options = {
213 "className":"FAQ.FAQClass",
214 "translationPrefix" : "faq.",
215 "tagCloud" : true,
216 "rowCount": 10
217 })
218 #livetable("faq" $columns $columnsProperties $options)
219 {{/velocity}}
220 {{/code}}
221
222 * Copy this code and paste it as Wiki content inside FAQ.WebHome
223 * Click "Save and View"
224 * New FAQ entries will now be displayed on the page once you create them
225
226 The FAQ.WebHome page should look similar to this:
227
228 {{image reference="FAQsLivetable.png"/}}
229
230 Notice how there are some translation keys displayed inside the livetable.
231 Let's create a translations document and change those keys to actual text:
232
233 * Create a new page inside the FAQ space called Translations
234 * Edit it in Wiki mode and paste this content inside:(((
235 {{code language="none"}}
236 faq.question=Question
237 faq.doc.creationDate=Creation Date
238 faq._actions=Actions
239 {{/code}}
240 )))
241 * Save & View
242 * Edit FAQ.Translations in Object mode and add a new XWiki.TranslationDocumentClass object
243 * Save & View again
244
245 Now the FAQ.WebHome page should look like this (notice the translations instead of the keys):
246
247 {{image reference="FAQsLivetableWithTranslations.png"/}}
248
249 === Using custom code ===
250
251 You will need to write the following code:
252
253 * A HQL query that will find all your FAQ documents
254 ** The HQL query looks for all documents that have a FAQ.FAQClass object other than the template
255 ** If no document has been created yet, a warning message is displayed
256 * A piece of velocity code to display all those documents
257 ** The velocity code loops in that list
258 ** For each item, the full document is loaded in memory so that values can be retrieved from it
259 ** For each document, the question is retrieved and displayed as a link towards the FAQ entry
260
261 Here is the resulting code:
262
263 {{code language="none"}}
264 = Existing FAQ entries =
265
266 {{velocity}}
267 #set($sql = ", BaseObject as obj where obj.name = doc.fullName and obj.className = 'FAQ.FAQClass' and obj.name <> 'FAQ.FAQTemplate'")
268 #set($results = $xwiki.searchDocuments($sql))
269 #if($results.empty)
270 No FAQ has been created yet!
271 #else
272 #foreach ($item in $results)
273 #set($faq = $xwiki.getDocument($item))
274 * [[${faq.display("question").replace("<p>", "").replace("</p>", "")}>>${item}]]
275 #end
276 #end
277 {{/velocity}}
278 {{/code}}
279
280 * Copy this code and paste it as Wiki content inside FAQ.WebHome
281 * Click "Save and View"
282 * New FAQ entries will now be displayed on the page once you create them
283
284 The FAQ.WebHome page should look similar to this:
285
286 {{image reference="FAQsCustomCode.png"/}}
287
288 == Creating new FAQ entries ==
289
290 There are 2 ways for you to let your users create new FAQ entries:
291
292 1. Declare the FAQ as a template
293 1. Add a custom creation form
294
295 === Using a Template ===
296
297 You will have to define a template provider [[as explained on this page>>extensions:Extension.Administration Application||anchor="HCreatethetemplateprovider"]]
298
299 Go to your wiki's administration interface, in the "Templates" section (Administration -> Content -> Templates). Create a new template provider in the "FAQ" space and name it "FAQTemplateProvider"
300
301 You can then use the following values:
302
303 * Provider name: "FAQ Template Provider"
304 * Template name "New FAQ entry"
305 * Template to use: "FAQ.FAQTemplate"
306
307 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.
308
309 === Custom creation form ===
310
311 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:
312
313 * The first part of the code checks whether the page has a parameter. If so:
314 ** The name of the document that will be created is computed
315 ** A check is done to verify the document doesn't exist yet
316 ** If everything's ok, the user is sent to the new document in inline edition mode
317 * The second part of the code is the actual FAQ creation form
318 ** It builds the name of the document to create it in the "FAQ" space
319 ** It sets the document parent as being the current document
320 ** It defines the template to use to create the new document
321
322 {{code language="none"}}
323 {{velocity}}
324 #if("$!request.docName" != '')
325 ## Request for creating a new instance
326 #set($docName = ${request.docName})
327 #set($targetDocName = "${request.spaceName}.${docName}")
328 #if(!$xwiki.exists($targetDocName) && $xwiki.hasAccessLevel('edit', $xcontext.user, $targetDocName))
329 $response.sendRedirect($xwiki.getURL($targetDocName, 'inline', "template=${escapetool.url($request.template)}&parent=${escapetool.url($request.parent)}"))
330 ## Stop processing, since we already sent a redirect.
331 #stop
332 #end
333 #end
334
335 = Add a new question =
336
337 #if("$!targetDocName" != '' && $xwiki.exists($targetDocName))
338 {{warning}}The target document already exists. Please choose a different name, or [[view the existing document>>$targetDocName]]{{/warning}}
339 #elseif("$!targetDocName" != '')
340 {{warning}}You don't have permission to create that document{{/warning}}
341 #end
342
343 {{html}}
344 <form action="" id="newdoc" method="post">
345 <div>
346 <input type="hidden" name="parent" value="${doc.fullName}"/>
347 <input type="hidden" name="template" value="FAQ.FAQTemplate"/>
348 <input type="hidden" name="sheet" value="1"/>
349 <input type="hidden" name="spaceName" value="FAQ"/>
350 Document: <input type="text" name="docName" value="Enter your question here" class="withTip" size="50"/>
351 <span class="buttonwrapper"><input type="submit" value="Create this FAQ" class="button"/></span>
352 </div>
353 </form>
354 {{/html}}
355 {{/velocity}}
356 {{/code}}
357
358 * Copy this code and paste it as Wiki content inside FAQ.WebHome, below the code that's already there
359 * Click "Save and View"
360 * A form to create new FAQ entries is now available on the page:(((
361 {{image reference="FAQsWithForm.png"/}}
362 )))
363
364 = Test the Application =
365
366 Now let's just create a new document in our application to test it out.
367 If you previously chose to use a "Custom creation form" for creating new FAQ entries, follow these steps:
368
369 * Go to FAQ.WebHome
370 * Below the "Add a new question" header, enter a question (which will also be used as the document title) in the //Document// field
371 * Click //Create this FAQ//
372 * You can then enter your question in longer form using the //Question// field on the template, like this:(((
373 {{image reference="FAQSheetEdit.PNG"/}}
374 )))
375 * Click //Save & View// and then you will see the newly created document, like this:(((
376 {{image reference="FAQSheetView.PNG"/}}
377 )))
378 * Go back to the "FAQ.WebHome" page to see the list of existing questions(((
379 {{image reference="FAQsWithEntry.png"/}}
380 )))
381
382 = Conclusion =
383
384 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.
385 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.
386
387 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