Wiki source code of Scripting API Guide

Version 40.2 by Vincent Massol on 2017/10/21

Show last authors
1 {{box cssClass="floatinginfobox" title="**Contents**"}}
2 {{toc/}}
3 {{/box}}
4
5 This guide covers the main XWiki APIs that you can use from scripts in wiki pages. It's not meant to be comprehensive. For that you'll need to check the [[XWiki Reference API page>>Documentation.DevGuide.API.WebHome]].
6
7 Note that while most examples are written in Velocity you can use [[any other scripting language>>Documentation.DevGuide.Scripting.WebHome]] to access the same APIs.
8
9 = Querying documents =
10
11 See the [[Query Module>>extensions:Extension.Query Module]] for examples on how to perform queries on the wiki using a scripting language.
12
13 = Create a new Document =
14
15 For example in Velocity:
16
17 {{code}}
18 ## Note that getDocument() creates a Document if it doesn't exist. This can be checked with $newDoc.isNew()
19 #set ($newDoc = $xwiki.getDocument('MySpace.MyPage'))
20 ## Set its content (for example)
21 #set ($discard = $newDoc.setContent("new content"))
22 ## The second parameter to save() indicates whether the save is a minor edit or not
23 #set ($discard = $newDoc.save("some comment explaining the save", true)
24 {{/code}}
25
26 = Accessing the request =
27
28 You can access the HTTP Request by accessing the ##com.xpn.xwiki.web.XWikiServletRequest## object through the ##request## script variable.
29
30 For example in Velocity, to access an ##action## HTTP parameter passed in the request you would write:
31
32 {{code language="velocity"}}
33 $request.action
34 {{/code}}
35
36 Note that this is a shortcut to:
37
38 {{code language="velocity"}}
39 $request.get("action")
40 {{/code}}
41
42 = Getting external content =
43
44 {{warning}}
45 Requires Programming Rights (since XWiki 9.10).
46 {{/warning}}
47
48 You can use the following APIs to get content located at external URLs:
49
50 {{code language="java"}}
51 public String getURLContent(String surl, String username, String password) throws IOException
52 public String getURLContent(String surl) throws IOException
53 public String getURLContent(String surl, String username, String password, int timeout) throws IOException
54 public String getURLContent(String surl, int timeout) throws IOException
55 public byte[] getURLContentAsBytes(String surl, String username, String password)
56 public byte[] getURLContentAsBytes(String surl) throws IOException
57 {{/code}}
58
59 For example in Velocity:
60
61 {{code language="velocity"}}
62 $xwiki.getURLContent("http://google.com")
63 {{/code}}
64
65 = Add objects to a page =
66
67 Here is a piece of Velocity script to show how is possible to store a new object in one page:
68
69 {{code language="velocity"}}
70 ## Create an object
71 #set($obj = $doc.newObject("XWiki.SomeClass"))
72 $obj.set("field1",$value1)
73 $obj.set("field2",$value2)
74
75 ## Save the object in the page
76 $doc.save()
77 {{/code}}
78
79 The "XWiki.SomeClass" class has to be created (through the class editor): field1 and field2 are property of the class. At the moment, this code works fine only if the user currently logged in has editing rights on the page, otherwise the Document.save() will not work.
80
81 = Access objects in a page =
82
83 Here is a piece of Velocity script to show how it is possible to access an object attached to the page, and read its fields :
84
85 {{code language="velocity"}}
86 ## Retrieve the first object (index [0]) among all objects attached to this page and of a certain class
87 #set($obj = $doc.getObject('SomeSpace.SomeClass'))
88
89 ## Retrieve the raw value of the propertty "field1" for this object, provided
90 ## a property called "field1" is actually defined in the class of this object
91 #set($rawValue = $obj.getProperty('field1').value)
92 SomeSpace.SomeClass[0] : field1 = "$rawValue"
93
94 ## or value displayed (supports l10n or key-value properties)
95 #set($ValueDisplayed = $obj.field1)
96
97 #set($class = $obj.xWikiClass) ## access the class object representing SomeSpace.SomeClass
98 ## return the property type: String, TextAreaDate, Boolean, ...
99 $class.get('field1').classType
100 {{/code}}
101
102
103 You can also go through all the properties of an object, without knowing their respective names. That's how the default Class Sheet works, when you create a class using the Class Wizard.
104
105 {{code language="velocity"}}
106 #set($class = $obj.xWikiClass) ## access the class object representing SomeSpace.SomeClass
107 #foreach($prop in $class.properties) ## go through all properties
108 <dt> *${prop.prettyName}* </dt>
109 <dd>$doc.display($prop.getName())</dd>
110 #end
111 {{/code}}
112
113 Actually the line {{code}}$doc.display(propertyName){{/code}} can either display the property value, or generate an input field in the page, mapped to the property whose name is passed as argument (when you edit the page in inline mode). If you have a Velocity script that uses the ##display(propertyName)## method to access properties of an object attached to the including page and you want to include it somewhere else you have to use the ##includeForm()## Velocity macro in the including script:
114
115 {{code language="velocity"}}
116 #includeForm("spacename.docname")
117 {{/code}}
118
119 See [[the includeForm() macro>>extensions:Extension.Include Form Macro]] for more information.
120
121 = Access objects from any page and loop over all objects of same Class =
122
123 Here is a piece of Velocity script to show how it is possible to access an object attached to the page from another page, and read its fields:
124 (It is similar than previous code except you must "call" page before with ##$xwiki.getDocument##.)
125
126 {{code language="velocity"}}
127 ## get the document which has the object (only one here) - this is the page where I can see things in the object editor
128 ## Retrieve the first object (index [0]) among all objects attached to the page MySpace.MyDocWithMyClassObjects and of a certain class MySpace.MyClass
129 #set( $MyDoc = $xwiki.getDocument("MySpace.MyDocWithMyClassObjects"))
130 ## get the document wich contains the class definition: this page has entries in the class editor
131 #set( $class = $xwiki.getClass("MySpace.MyClass"))
132 #foreach($prop in $class.properties) ## go through all properties
133 * ${prop.prettyName} : $MyDoc.display($prop.getName())
134 #end
135 {{/code}}
136
137 If ##MySpace.MyDocWithMyClassObjects## have many attached objects of ##MySpace.MyClass## class (with different value)
138 {{image reference="APIGuide-MyDocWithMyClassObjects.png"/}} {{image reference="APIGuide-ResultOfLoops.png"/}}
139
140 {{code language="velocity"}}
141 ## if you have more than one object on a page, you will have to loop over them and use "$doc.use"
142 #set($MyDoc = $xwiki.getDocument("MySpace.MyDocWithMyClassObjects"))
143 #set($class = $xwiki.getClass("MySpace.MyClass"))
144 ## loop over all objects
145 #foreach($obj in $MyDoc.getObjects("MySpace.MyClass"))
146 * Object number $velocityCount
147 #set($discard = $MyDoc.use($obj))
148 #foreach($prop in $class.properties) ## go through all properties
149 ** ${prop.prettyName} : $MyDoc.display($prop.getName())
150 #end
151 #end
152 {{/code}}
153
154 = Include a Velocity page into another Velocity page =
155
156 See the [[Include In Velocity tutorial>>FAQ.IncludeInVelocity]].
157
158 = Redirecting to another page =
159
160 It's possible to redirect the user to another page. This is useful for example when a page has been removed and you have given the URL to someone so you want the old page to redirect to the new page.
161
162 Example:
163
164 {{code language="velocity"}}
165 $response.sendRedirect($xwiki.getURL("Space.Page"))
166 {{/code}}
167
168 For more examples, see the [[Redirect Snippet>>snippets:Extension.Redirect]].
169
170 = Add an Attachment to a page =
171
172 For example, in Velocity:
173
174 {{code}}
175 {{velocity}}
176 #set($content = "This is some small arbitrary content")
177 #set($discard = $doc.addAttachment("myfile.txt", $content.getBytes()))
178 #set($discard = $doc.save("some comment"))
179 {{/velocity}}
180 {{/code}}
181
182 = Add a new user to a List of Users xobject =
183
184 Let's imagine that ##Space.Page## contains an xobject having a ##users## xproperty of type "List of Users" (and configured to be a multiselect).
185
186 The following code adds a new user reference to the list:
187
188 {{code}}
189 {{velocity}}
190 #set ($usersObject = $doc.getObject('Space.Page'))
191 #set ($referenceList = $usersObject.getValue('users'))
192 #set ($referenceList = "${referenceList},XWiki.NewUser")
193 #set ($discard = $usersObject.set('users', $referenceList))
194 #set ($discard = $doc.save('Added new user', true))
195 {{velocity}}
196 {{/code}}
197
198 = Create an XClass =
199
200 The following example creates an XClass with a single ##mytextarea## xproperty of type Text Area in the document ##Sandbox.TestClass##.
201
202 {{warning}}
203 Requires Programming Rights
204 {{/warning}}
205
206 {{code}}
207 {{velocity}}
208 #set ($mydoc = $xwiki.getDocument('Sandbox.TestClass'))
209 #set ($myinternaldoc = $mydoc.getDocument())
210 #set ($myclass = $myinternaldoc.getXClass())
211 #set ($discard = $myclass.addTextAreaField("mytextarea", "My Text Area", 100, 5))
212 #set ($discard = $mydoc.save('created doc + xclass'))
213 {{/velocity}}
214 {{/code}}
215
216 = Modify the last update date =
217
218 {{warning}}
219 Requires Programming Rights
220 {{/warning}}
221
222 {{code}}
223 {{velocity}}
224 #set ($mydoc = $xwiki.getDocument('Sandbox.WebHome'))
225 #set ($date = $datetool.toDate('yyyy-MM-dd', '2013-01-01'))
226 #set ($mydocinternal = $mydoc.getDocument())
227 #set ($discard = $mydocinternal.setDate($date))
228 #set ($discard = $mydocinternal.setMetaDataDirty(false))
229 #set ($discard = $mydocinternal.setContentDirty(false))
230 $xwiki.getXWiki().saveDocument($mydocinternal, "change update date", true, $xcontext.getContext())
231 {{/velocity}}
232 {{/code}}
233
234 = Find XDOM Blocks =
235
236 You can access an AST (we all it the XDOM) of a document's content using the ##getXDOM()## API (See [[Rendering Documentation>>rendering:Main.WebHome]] for more). Then you can find all Blocks of a given type.
237
238 For example to find all Headings in ##Sandbox.WebHome## you could write:
239
240 {{code}}
241 {{velocity}}
242 #set ($mydoc = $xwiki.getDocument('Sandbox.WebHome'))
243 #foreach ($block in $mydoc.getXDOM().getBlocks('class:HeaderBlock', 'DESCENDANT'))
244 * $block
245 #end
246 {{/velocity}}
247 {{/code}}

Get Connected