Wiki source code of Scripting API Guide

Version 38.1 by Vincent Massol on 2017/10/11

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 You can use the following APIs to get content located at external URLs:
45
46 {{code language="java"}}
47 public String getURLContent(String surl, String username, String password) throws IOException
48 public String getURLContent(String surl) throws IOException
49 public String getURLContent(String surl, String username, String password, int timeout) throws IOException
50 public String getURLContent(String surl, int timeout) throws IOException
51 public byte[] getURLContentAsBytes(String surl, String username, String password)
52 public byte[] getURLContentAsBytes(String surl) throws IOException
53 {{/code}}
54
55 For example in Velocity:
56
57 {{code language="velocity"}}
58 $xwiki.getURLContent("http://google.com")
59 {{/code}}
60
61 = Add objects to a page =
62
63 Here is a piece of Velocity script to show how is possible to store a new object in one page:
64
65 {{code language="velocity"}}
66 ## Create an object
67 #set($obj = $doc.newObject("XWiki.SomeClass"))
68 $obj.set("field1",$value1)
69 $obj.set("field2",$value2)
70
71 ## Save the object in the page
72 $doc.save()
73 {{/code}}
74
75 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.
76
77 = Access objects in a page =
78
79 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 :
80
81 {{code language="velocity"}}
82 ## Retrieve the first object (index [0]) among all objects attached to this page and of a certain class
83 #set($obj = $doc.getObject('SomeSpace.SomeClass'))
84
85 ## Retrieve the raw value of the propertty "field1" for this object, provided
86 ## a property called "field1" is actually defined in the class of this object
87 #set($rawValue = $obj.getProperty('field1').value)
88 SomeSpace.SomeClass[0] : field1 = "$rawValue"
89
90 ## or value displayed (supports l10n or key-value properties)
91 #set($ValueDisplayed = $obj.field1)
92
93 #set($class = $obj.xWikiClass) ## access the class object representing SomeSpace.SomeClass
94 ## return the property type: String, TextAreaDate, Boolean, ...
95 $class.get('field1').classType
96 {{/code}}
97
98
99 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.
100
101 {{code language="velocity"}}
102 #set($class = $obj.xWikiClass) ## access the class object representing SomeSpace.SomeClass
103 #foreach($prop in $class.properties) ## go through all properties
104 <dt> *${prop.prettyName}* </dt>
105 <dd>$doc.display($prop.getName())</dd>
106 #end
107 {{/code}}
108
109 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:
110
111 {{code language="velocity"}}
112 #includeForm("spacename.docname")
113 {{/code}}
114
115 See [[the includeForm() macro>>extensions:Extension.Include Form Macro]] for more information.
116
117 = Access objects from any page and loop over all objects of same Class =
118
119 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:
120 (It is similar than previous code except you must "call" page before with ##$xwiki.getDocument##.)
121
122 {{code language="velocity"}}
123 ## get the document which has the object (only one here) - this is the page where I can see things in the object editor
124 ## Retrieve the first object (index [0]) among all objects attached to the page MySpace.MyDocWithMyClassObjects and of a certain class MySpace.MyClass
125 #set( $MyDoc = $xwiki.getDocument("MySpace.MyDocWithMyClassObjects"))
126 ## get the document wich contains the class definition: this page has entries in the class editor
127 #set( $class = $xwiki.getClass("MySpace.MyClass"))
128 #foreach($prop in $class.properties) ## go through all properties
129 * ${prop.prettyName} : $MyDoc.display($prop.getName())
130 #end
131 {{/code}}
132
133 If ##MySpace.MyDocWithMyClassObjects## have many attached objects of ##MySpace.MyClass## class (with different value)
134 {{image reference="APIGuide-MyDocWithMyClassObjects.png"/}} {{image reference="APIGuide-ResultOfLoops.png"/}}
135
136 {{code language="velocity"}}
137 ## if you have more than one object on a page, you will have to loop over them and use "$doc.use"
138 #set($MyDoc = $xwiki.getDocument("MySpace.MyDocWithMyClassObjects"))
139 #set($class = $xwiki.getClass("MySpace.MyClass"))
140 ## loop over all objects
141 #foreach($obj in $MyDoc.getObjects("MySpace.MyClass"))
142 * Object number $velocityCount
143 #set($discard = $MyDoc.use($obj))
144 #foreach($prop in $class.properties) ## go through all properties
145 ** ${prop.prettyName} : $MyDoc.display($prop.getName())
146 #end
147 #end
148 {{/code}}
149
150 = Include a Velocity page into another Velocity page =
151
152 See the [[Include In Velocity tutorial>>FAQ.IncludeInVelocity]].
153
154 = Redirecting to another page =
155
156 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.
157
158 Example:
159
160 {{code language="velocity"}}
161 $response.sendRedirect($xwiki.getURL("Space.Page"))
162 {{/code}}
163
164 For more examples, see the [[Redirect Snippet>>snippets:Extension.Redirect]].
165
166 = Add an Attachment to a page =
167
168 For example, in Velocity:
169
170 {{code}}
171 {{velocity}}
172 #set($content = "This is some small arbitrary content")
173 #set($discard = $doc.addAttachment("myfile.txt", $content.getBytes()))
174 #set($discard = $doc.save("some comment"))
175 {{/velocity}}
176 {{/code}}
177
178 = Add a new user to a List of Users xobject =
179
180 Let's imagine that ##Space.Page## contains an xobject having a ##users## xproperty of type "List of Users" (and configured to be a multiselect).
181
182 The following code adds a new user reference to the list:
183
184 {{code}}
185 {{velocity}}
186 #set ($usersObject = $doc.getObject('Space.Page'))
187 #set ($referenceList = $usersObject.getValue('users'))
188 #set ($referenceList = "${referenceList},XWiki.NewUser")
189 #set ($discard = $usersObject.set('users', $referenceList))
190 #set ($discard = $doc.save('Added new user', true))
191 {{velocity}}
192 {{/code}}
193
194 = Create an XClass =
195
196 The following example creates an XClass with a single ##mytextarea## xproperty of type Text Area in the document ##Sandbox.TestClass##.
197
198 {{warning}}
199 Requires Programming Rights
200 {{/warning}}
201
202 {{code}}
203 {{velocity}}
204 #set ($mydoc = $xwiki.getDocument('Sandbox.TestClass'))
205 #set ($myinternaldoc = $mydoc.getDocument())
206 #set ($myclass = $myinternaldoc.getXClass())
207 #set ($discard = $myclass.addTextAreaField("mytextarea", "My Text Area", 100, 5))
208 #set ($discard = $mydoc.save('created doc + xclass'))
209 {{/velocity}}
210 {{/code}}
211
212 = Modify the last update date =
213
214 {{warning}}
215 Requires Programming Rights
216 {{/warning}}
217
218 {{code}}
219 {{velocity}}
220 #set ($mydoc = $xwiki.getDocument('Sandbox.WebHome'))
221 #set ($date = $datetool.toDate('yyyy-MM-dd', '2013-01-01'))
222 #set ($mydocinternal = $mydoc.getDocument())
223 #set ($discard = $mydocinternal.setDate($date))
224 #set ($discard = $mydocinternal.setMetaDataDirty(false))
225 #set ($discard = $mydocinternal.setContentDirty(false))
226 $xwiki.getXWiki().saveDocument($mydocinternal, "change update date", true, $xcontext.getContext())
227 {{/velocity}}
228 {{/code}}
229
230 = Find XDOM Blocks =
231
232 You can access an AST of a document's content using the ##getXDOM()## API. Then you can find all Blocks of a given type.
233
234 For example to find all Headings in ##Sandbox.WebHome## you could write:
235
236 {{code}}
237 {{velocity}}
238 #set ($mydoc = $xwiki.getDocument('Sandbox.WebHome'))
239 #foreach ($block in $mydoc.getXDOM().getBlocks('class:HeaderBlock', 'DESCENDANT'))
240 * $block
241 #end
242 {{/velocity}}
243 {{/code}}

Get Connected