Creating a FAQ Application (Manual)

Last modified by Simon Urli on 2023/10/10

This tutorial will show you how to build a Frequently Asked Questions (FAQs) Application much like the one you can find on the FAQ page. This is a very simple application that makes use of XWiki's classes, properties, and objects. It also uses a technique that you may frequently use as the basis for several different kinds of applications.

It's also possible to follow this tutorial as a video tutorial on Youtube.

Prerequisites for following the tutorial

If you've already followed the AWM FAQ Tutorial or installed the FAQ Application you'll need to do one of 2 things before you can take this tutorial:

  • Delete the FAQ space (if you've followed the AWM FAQ Tutorial) or uninstall the FAQ Application (if you've installed the FAQ Application)
  • 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.

You should have installed XWiki and have a basic understanding of how to use it.

All through this tutorial you should refer to the XWiki Data Model for information on XWiki's data model. You might also use the XWiki Scripting Guide 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.

Make sure that your user is an Advanced user before following this tutorial since you'll need for example to use the wiki editor (Wiki > Edit menu).

Application Overview

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.

Let us begin by taking a look at what we are going to build. The new application will have the following views:

  • An FAQ entry in View mode (notice that the properties can be edited in-place starting with XWiki 12.4RC1)

    FAQSheetView.PNG

  • An FAQ entry in Edit mode

    FAQSheetEdit.PNG

Authoring Templates and Page Design Sheets

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.

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.

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 an XWiki Document can contain objects and this is the case of an authoring template: it is an 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.

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.

Go to the Class Editor Wizard

Five pages, which collectively make up an 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. 

Create the FAQ Class

  • 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:

    CreateANewClass1.png

  • 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 add the suffix Class to the page name(you could also enter FAQClass as the page name directly).
  • 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.

    CreateANewClass2.png

  • 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.
  • Click the "Create this Class" button. You should then see a page with the following content:
    {{velocity}}
    ## Replace the default space with the space where you want your documents to be created.
    ## Replace the default parent with the one of your choice and save the document.
    ##
    #set($defaultSpace = $doc.space)
    #set($defaultParent = $doc.fullName)
    {{/velocity}}

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.
The line of code should look like this:

#set($defaultSpace = 'FAQ')

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.
The line of code should look like this:

#set($defaultParent = 'FAQ.WebHome')

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:

FAQClass1.PNG

Add Properties to the Class

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!

  • Click on the 'class editor' link
  • 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.

In our document, we'll store both a question and an answer. So we need to create a property for each of them.

  • Enter the text question in the "name" field
  • 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.

    AddQuestionProperty.PNG

  • Click on the "+" icon to expand the options for the newly created property
  • Change the value of the "Pretty Name" field to "Question"(capital Q):

    QuestionProperty.PNG

  • Now create another property called answer the same way that you did for the previous "question" property (choose TextArea for the property type)
  • Expand it from the property list and change the value of the "Pretty Name" field to "Answer"
  • When you are done adding and configuring the properties, click the "Save & View" button

Create the Page Design Sheet

  • After the previous step you are now on the FAQClass page which should look like this:

    FAQClass2.PNG

  • 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.
  • 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:
    • It adds an object of type XWiki.ClassSheetBinding to the FAQ.FAQClass" document. Basically it ties the FAQ Class to the Sheet.
    • It's because of this object that users will be sent to form edition mode when editing FAQ entries
  • 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:
    {{velocity}}
    ## You can modify this page to customize the presentation of your object.
    ## At first you should keep the default presentation and just save the document.

    ## We have to use wiki=true because $doc.display() can produce wiki syntax.
    {{html wiki="true" clean="false"}}
    ## Load the JavaScript code required to make the object properties editable in-place.
    #set ($discard = $xwiki.jsfx.use('uicomponents/edit/editableProperty.js', {
      'forceSkinAction': true,
      'language': $xcontext.locale
    }))
    #set ($editing = $xcontext.action == 'edit')
    ## The object to display.
    #set ($xobject = $doc.getObject('FAQ.FAQClass'))
    ## The class that describes the object properties.
    #set ($xclass = $xobject.xWikiClass)
    ## Make sure the following display* method calls use the right object.
    #set ($discard = $doc.use($xobject))
    ## Using the xform vertical form layout.
    <div class="xform">
      <dl>
      #foreach ($property in $xclass.properties)
        <dt #if (!$editing && $hasEdit)
            class="editableProperty"
            #set ($xobjectPropertyReference = $xobject.getProperty($property.name).reference)
            data-property="$escapetool.xml($services.model.serialize($xobjectPropertyReference))"
            data-property-type="object"#end>
          ## This must match the id generated by the $doc.display() method below.
          #set ($propertyId = "${xclass.name}_${xobject.number}_$property.name")
          <label#if ($editing) for="$escapetool.xml($propertyId)"#end>
            $escapetool.xml($property.translatedPrettyName)
          </label>
          ## Support for specifying a translation key as hint in the property definition.
          <span class="xHint">$!escapetool.xml($services.localization.render($property.hint))</span>
        </dt>
        <dd>$doc.display($property.name)</dd>
      #end
      #if (!$xclass.properties || $xclass.properties.size() == 0)
        ## Keep the empty definition term in order to have valid HTML.
        <dt></dt>
        <dd>$escapetool.xml($services.localization.render('xclass.defaultObjectSheet.noProperties'))</dd>
      #end
      </dl>
    </div>
    {{/html}}
    {{/velocity}}

    Let's take a moment now and analyze this code:

    • first, it loads the JavaScript required for in-place editing
    • then it retrieves the FAQ object from the current page and the FAQ class defintion
    • then it iterates through all the FAQ class properties displaying:
      • the translated pretty name
      • the translated hint
      • the value from the FAQ object in view mode, or the form field used to input or modify the value in edit mode
    • it uses a definition list to display the FAQ object, following the Vertical Form layout

    As we mentioned, XWiki provides a mechanism that helps us create sheets used for both view and edit mode. This is the display function used in the line:

    <dd>$doc.display($property.name)</dd>

    It detects the current mode (edit or view) and displays the property referenced by its argument as the mode dictates:

    • in view mode it will display the value of the property
    • in edit mode it will display a form field that will allow the user to edit it

    This way we can use a single Design Sheet to both display and edit our FAQ entries. See the XWiki API reference and XWiki Scripting pages for more details about this.

  • Click "Save & View"

Create the Authoring Template

  • Navigate back to the FAQ.FAQClass document (you can use the arrows in the breadcrumb to do so). The document should look like this:

    FAQClass3.PNG

  • Click on the "Create the document template" button. The Authoring Template will be automatically created.

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 for more information regarding this technique.

Now we need to associate the prototype object with this document to turn it into a true authoring template:

  • If you're on the template page, navigate back to the FAQ.FAQClass document.
  • 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 »."
  • Click on "Add a FAQ object to the template »":

    FAQObject.png

Next, we want to remove the title for the newly created template:

  • Navigate to the FAQ.FAQTemplate document (you can click on the "View the template page (FAQ / FAQ Template)" link for doing that for example.
  • Edit this document in Wiki mode
  • Inside the Title field you have "FAQ Template" written -> delete this text
  • Save & View

This step is needed so that all of our future entries don't have "FAQ Template" as their title.

Congratulations: you just created an Authoring Template! You're almost done now.

FAQClass4.PNG

Create the Template Provider

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.
The template provider is created with some default values, but those can be updated to match the needs.

Create a home page for the FAQ application

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.

Thus we now need to create the FAQ.WebHome page

  • Click on "FAQ" in the breadcrumb to navigate to FAQ.WebHome and notice that the page doesn't exist.
  • Edit it in wiki mode
  • Type in the title "FAQs"

Displaying existing FAQ entries

You have 3 options when it comes to displaying existing FAQ entries:

  1. Use the Live Data macro
  2. Use the Livetable component Not described below as LiveData is now the advised option
  3. Write custom code in order to display them

Using the Live Data macro

In this section, we will show how to use the Live Data macro to display the existing questions.

The Live Data macro will give users the ability to easily list and filter through existing FAQ pages. The macro parameters defines:

  • the id of the table
  • the source liveTable is a bridge to reuse existing Livetable sources
  • the list of properties to display
  • the source parameters defines addition parameters specific to the liveTable source: the translation prefix to use, and the XClass to list

In addition, the body of the macro defines additional display customizations. We use a link displayer to wrap the question with a link to the page containing the FAQ XObject.

{{liveData
  id="faq"
  source='liveTable'
  properties='question,doc.creationDate,_actions'
  sourceParameters="translationPrefix=faq.&className=XWiki.FAQClass"
}}{
  "meta": {
    "propertyDescriptors": [
      {
        "id": "question",
        "displayer": {"id": "link", "html": true}
      }
    ]
  }
}{{/liveData}}
  • Copy this code and paste it as Wiki content (inside FAQ.WebHome)
  • Click "Save and View"
  • New FAQ entries will now be displayed on the page once you create them

The FAQ.WebHome page should look similar to this:

FAQsLiveData.png

Notice how there are some translation keys displayed inside the Live Data table. Let's create a translations document and change those keys to actual text:

  • Create a new page inside the FAQ space called Translations, i.e. at FAQ.Translations (using the "+" button)
  • Edit it in Wiki mode and paste this content inside:
    faq.question=Question
    faq.doc.creationDate=Creation Date
    faq._actions=Actions
  • Click "Save & View"
  • 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.
  • Click "Save & View" again

Now the FAQ.WebHome page should look like this (notice the translations instead of the keys):

  FAQsLiveDataWithTranslations.png

Using custom code

You will need to write the following code:

  • An XWQL query that will find all your FAQ documents. Check the Query API documentation to know more about it.
    • The XWQL query looks for all documents that have a FAQ.FAQClass object other than the template
    • If no document has been created yet, a warning message is displayed
  • A piece of velocity code to display all those documents
    • The velocity code loops in that list
    • For each item, the full document is loaded in memory so that values can be retrieved from it
    • For each document, the question is retrieved and displayed as a link towards the FAQ entry

Here is the resulting code:

= Existing FAQ entries =

{{velocity}}
#set($xwql = "from doc.object(FAQ.FAQClass) as faq where doc.fullName <> 'FAQ.FAQTemplate'")
#set($results = $services.query.xwql($xwql).execute())
#if($results.empty)
  No FAQ has been created yet!
#else
  #foreach ($item in $results)
    #set($faq = $xwiki.getDocument($item))
    * [[${faq.display("question").replace("<p>", "").replace("</p>", "")}>>${item}]]
  #end
#end
{{/velocity}}
  • Copy this code and paste it as Wiki content inside FAQ.WebHome
  • Click "Save and View"
  • New FAQ entries will now be displayed on the page once you create them

The FAQ.WebHome page should look similar to this:

FAQsCustomCode.png

Creating new FAQ entries

There are 2 ways for you to let your users create new FAQ entries:

  1. Declare the FAQ as a template
  2. Add a custom creation form

Using a Template

You will have to define a template provider as explained on this page

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

You can then use the following values:

  • Provider name: FAQ Template Provider
  • Template name: New FAQ entry
  • Template to use: FAQ.FAQTemplate

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.

Custom creation form

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:

  • The first part of the code checks whether the page has a parameter. If so:
    • The name of the document that will be created is computed
    • A check is done to verify the document doesn't exist yet
    • If everything's ok, the user is sent to the new document in inline edition mode
  • The second part of the code is the actual FAQ creation form
    • It builds the name of the document to create it in the FAQ space
    • It sets the document parent as being the current document
    • It defines the template to use to create the new document
{{velocity}}
#if("$!request.docName" != '')
  ## Request for creating a new instance
  #set($docName = ${request.docName})
  #set($targetDocName = "${request.spaceName}.${docName}")
  #if(!$xwiki.exists($targetDocName) && $xwiki.hasAccessLevel('edit', $xcontext.user, $targetDocName))
    $response.sendRedirect($xwiki.getURL($targetDocName, 'inline', "template=${escapetool.url($request.template)}&parent=${escapetool.url($request.parent)}"))
    ## Stop processing, since we already sent a redirect.
    #stop
  #end
#end

= Add a new question =

#if("$!targetDocName" != '' && $xwiki.exists($targetDocName))
  {{warning}}The target document already exists. Please choose a different name, or [[view the existing document>>$targetDocName]]{{/warning}}
#elseif("$!targetDocName" != '')
  {{warning}}You don't have permission to create that document{{/warning}}
#end

{{html}}
  <form action="" id="newdoc" method="post">
    <div>
      <input type="hidden" name="parent" value="${doc.fullName}"/>
      <input type="hidden" name="template" value="FAQ.FAQTemplate"/>
      <input type="hidden" name="sheet" value="1"/>
      <input type="hidden" name="spaceName" value="FAQ"/>
      Document: <input type="text" name="docName" value="Enter your question here" class="withTip" size="50"/>
      <span class="buttonwrapper"><input type="submit" value="Create this FAQ" class="button"/></span>
    </div>
  </form>
{{/html}}
{{/velocity}}
  • Copy this code and paste it as Wiki content inside FAQ.WebHome, below the code that's already there
  • Click "Save and View"
  • A form to create new FAQ entries is now available on the page:

    FAQsWithForm.png

Test the Application

Now let's just create a new document in our application to test it out.

If you previously chose to use a "Custom creation form" for creating new FAQ entries, follow these steps:

  • Go to FAQ.WebHome
  • Below the "Add a new question" header, enter a question (which will also be used as the document title) in the Document field
  • Click Create this FAQ
  • You can then enter your question in longer form using the Question field on the template, like this:

    FAQSheetEdit.PNG

  • Click Save & View and then you will see the newly created document, like this:

    FAQSheetView.PNG

  • Go back to the FAQ.WebHome page (you can use the breadcrumbs) to see the list of existing questions

    FAQsWithEntry.png

Conclusion

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.

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.

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.

Tags:
   

Get Connected