How can I create a new page based on a form?

Last modified by Thomas Mortagne on 2023/10/10

The general strategy is:

  • Use the {{html}} macro to create the form
  • Don't use any action value so that when the submit button of the form is hit the same page is called
  • Use the {{velocity}} macro to handle when the page is called again with the values from the form and redirect to an XWiki URL that creates the new page, passing in parameters the template name and parent page.
  • Create a page which you'll use as a template. Add all XObjects you need to that template page. The XWiki URL mentioned above will copy this template page to the new page.

For example if you have a FAQ.FAQTemplate template page and you wish to have a form to create a new FAQ page located in the FAQ space you could write (See this part of the FAQ Tutorial for more details):

{{velocity}}
#if("$!request.docName" != '')
  ## Request for creating a new instance
  #set($targetDocReference = $services.model.createDocumentReference('', $!{request.spaceName}, $!{request.docName}))
 $response.sendRedirect($xwiki.getURL($targetDocReference, 'inline', "template=${escapetool.url($request.template)}&parent=${escapetool.url($request.parent)}"))
  ## Stop processing, since we already sent a redirect.
  #stop
#end

= Add a new question =

{{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}}

Note, if you want to create a new FAQ page located in some nested space under the FAQ space, you could write:

{{velocity}}
#if("$!request.docName" != '')
  ## Request for creating a new instance
  ## Add location where to create the new page: FAQ.NestedSpace1.NestedSpace2
  #set ($Location= ["$!{request.spaceName}", 'NestedSpace1', 'NestedSpace2'])
  #set($targetDocReference = $services.model.createDocumentReference('', $!{Location}, "$!{request.docName}"))
  $response.sendRedirect($xwiki.getURL($targetDocReference, 'inline', "template=${escapetool.url($request.template)}&parent=${escapetool.url($request.parent)}"))
  ## Stop processing, since we already sent a redirect.
  #stop
#end

= Add a new question =
...
Tags:
   

Get Connected