Wiki-Quellcode von ClassEditSheet

Zuletzt geändert von Holger Engels am 2026/09/22 10:06

Zeige letzte Bearbeiter
1 {{include reference="AppWithinMinutes.VelocityMacros" /}}
2
3 {{groovy}}
4 import com.xpn.xwiki.XWikiContext;
5 import com.xpn.xwiki.api.Context;
6 import com.xpn.xwiki.api.Object;
7 import com.xpn.xwiki.api.PropertyClass;
8 import com.xpn.xwiki.doc.XWikiDocument;
9 import com.xpn.xwiki.objects.BaseObject;
10
11 /**
12 * Used to preview class fields that have a custom display associated, before they are actually added/saved to the
13 * class. For instance, when the user drags a Date field from the palette to the field canvas the class editor needs to
14 * display that Date field as if the user would be editing an object with this Date field in "Inline form" edit mode.
15 * This means that if the Date field has a custom display, the custom display should be used (e.g. using a Date picker).
16 */
17 class PropertyCustomDisplayer
18 {
19 private XWikiContext context;
20
21 public PropertyCustomDisplayer(Context context)
22 {
23 this.context = context.getContext();
24 }
25
26 public String display(PropertyClass property, String prefix, com.xpn.xwiki.api.Object object)
27 {
28 HashMap<String, Object> backup = new HashMap<String, Object>();
29 try {
30 XWikiDocument.backupContext(backup, this.context);
31 return this.displayInternal(property.getPropertyClass(), prefix, object.getXWikiObject());
32 } finally {
33 XWikiDocument.restoreContext(backup, this.context);
34 }
35 }
36
37 private String displayInternal(com.xpn.xwiki.objects.classes.PropertyClass property, String prefix, BaseObject object)
38 {
39 StringBuffer result = new StringBuffer();
40 property.displayCustom(result, property.getName(), prefix, "edit", object, this.context);
41 return result.toString();
42 }
43 }
44 xcontext.put('propertyCustomDisplayer', new PropertyCustomDisplayer(xcontext))
45 {{/groovy}}
46
47 {{velocity output="false"}}
48 #**
49 * Constants
50 *#
51 ## Magic date used to mark in AWM that the date field is not set for the current entry. See https://jira.xwiki.org/browse/XWIKI-10296
52 #set($MAGIC_DATE = $datetool.toDate('yyyy-MM-dd', '9999-12-31'))
53
54 #**
55 * Displays the field palette.
56 *#
57 #macro (displayFieldPalette)
58 <div id="palette">
59 <p><strong>$services.localization.render('platform.appwithinminutes.classEditorPaletteTitle')</strong></p>
60 <p class="xHint">$services.localization.render('platform.appwithinminutes.classEditorPaletteHint')</p>
61 ## List all form field types, grouped by category.
62 #set ($formFieldDocs = [])
63 #set ($formFieldClassName = 'AppWithinMinutes.FormFieldClass')
64 #set ($categoryListStatement = 'from doc.object(AppWithinMinutes.FormFieldCategoryClass) as category order by category.priority')
65 <ul>
66 #foreach ($category in $services.query.xwql($categoryListStatement).execute())
67 #set ($categoryDoc = $xwiki.getDocument($category))
68 <li>
69 <div class="category">$escapetool.xml($categoryDoc.plainTitle)</div>
70 #set ($formFieldsForCategoryStatement = "from doc.object($formFieldClassName) as field where field.category = :category order by field.priority")
71 #set ($formFieldsForCategoryQuery = $services.query.xwql($formFieldsForCategoryStatement).bindValue('category', $category))
72 <ul>
73 #foreach ($formField in $formFieldsForCategoryQuery.execute())
74 #set ($formFieldDoc = $xwiki.getDocument($formField))
75 #set ($discard = $formFieldDocs.add($formFieldDoc))
76 #set ($formFieldIcon = $formFieldDoc.getObject($formFieldClassName).getProperty('icon').value)
77 #set ($formFieldIconRendered = $services.icon.renderHTML($formFieldIcon))
78 #if ("$!formFieldIconRendered" == "")
79 #if ($formFieldIcon.contains('/'))
80 #set ($formFieldIconURL = $xwiki.getSkinFile($formFieldIcon))
81 #else
82 #set ($formFieldIconURL = $formFieldDoc.getAttachmentURL($formFieldIcon))
83 #end
84 #set ($formFieldIconRendered = "<img src='$escapetool.xml($formFieldIconURL)' alt='$escapetool.xml($formFieldDoc.plainTitle)' class='icon' />")
85 #end
86 <li class="field">
87 $formFieldIconRendered
88 $escapetool.xml($formFieldDoc.plainTitle)
89 ## FIXME: We should use the 'get' action instead to prevent the stats module from recording this AJAX request.
90 ## The 'edit' action is a temporary solution until the sheet module is modified to allow a sheet to be enforced through
91 ## the query string even if it doesn't match the action (e.g. the 'get' action).
92 ## The sheet parameter is required when editing a new class because the request will be made to a document that doesn't exist.
93 ## FIXME2: In the future don't force the text editor type and instead use the default editor. This means
94 ## that if the WYSIWYG editor is used, we'll need to convert the HTML into the target syntax so that the
95 ## Template in #updateAndSaveTemplate is saved with target syntax and not HTML.
96 ## See https://jira.xwiki.org/browse/XWIKI-13789
97 #set ($fieldURL = $doc.getURL('edit', $escapetool.url({
98 'xpage': 'plain',
99 'sheet': 'AppWithinMinutes.ClassEditSheet',
100 'form_token': $services.csrf.getToken(),
101 'template': 'AppWithinMinutes.ClassTemplate',
102 'field': $formFieldDoc.fullName,
103 'xeditmode': 'text'
104 })))
105 <input type="hidden" value="$escapetool.xml($fieldURL)" class="data"/>
106 </li>
107 #end
108 </ul>
109 </li>
110 #end
111 </ul>
112 </div>
113 #end
114
115 #**
116 * Displays the field canvas.
117 *#
118 #macro (displayFieldCanvas)
119 #set ($propertyType2FormField = {})
120 #foreach ($formFieldDoc in $formFieldDocs)
121 ## Use the type of the field template.
122 #set ($type = $formFieldDoc.getxWikiClass().properties.get(0).classType)
123 #set ($discard = $propertyType2FormField.put($type, $formFieldDoc))
124 #end
125 <div id="canvas">
126 <p class="hint">
127 $services.localization.render('platform.appwithinminutes.classEditorCanvasHint')
128 </p>
129 <ul>
130 #set ($unknownFields = [])
131 #foreach ($field in $doc.getxWikiClass().properties)
132 #set ($formFieldDoc = $propertyType2FormField.get($field.classType))
133 #if ($formFieldDoc)
134 <li>#displayField($field $formFieldDoc)</li>
135 #else
136 #set($discard = $unknownFields.add($field))
137 #end
138 #end
139 </ul>
140 <div class="hidden">
141 ## Output the field meta data even if the field is not supported to preserve it when the class is saved.
142 #foreach ($field in $unknownFields)
143 #displayFieldMetaData($field)
144 #end
145 </div>
146 </div>
147 #end
148
149 #**
150 * Display the options to create/update the class template, the class sheet and the class translation bundle.
151 *#
152 #macro (displayClassOptions)
153 #set ($className = $stringtool.removeEnd($doc.fullName, 'Class'))
154 #set ($templateReference = $services.model.resolveDocument("${className}Template"))
155 #set ($translationsReference = $services.model.resolveDocument("${className}Translations"))
156 #set ($classSheets = $services.sheet.getClassSheets($doc))
157 #set ($sheetReference = $null)
158 #if ($classSheets.isEmpty())
159 #set ($sheetReference = $services.model.resolveDocument("${className}Sheet"))
160 #elseif ($classSheets.size() == 1)
161 #set ($sheetReference = $classSheets.get(0))
162 #end
163 ## Hide the options if neither the sheet nor the template nor the translation bundle exists. They don't have to be
164 ## updated, they have to be created.
165 <dl id="options" #if (!$xwiki.exists($sheetReference) && !$xwiki.exists($templateReference)
166 && !$xwiki.exists($translationsReference))class="hidden"#end>
167 <dt>
168 <label for="updateClassTemplate">
169 <input type="checkbox" id="updateClassTemplate" name="updateClassTemplate" checked="checked" />
170 $services.localization.render('platform.appwithinminutes.classEditorUpdateTemplateLabel')
171 </label>
172 </dt>
173 <dd>
174 <span class="xHint">
175 $services.localization.render('platform.appwithinminutes.classEditorUpdateTemplateHint',
176 ["#pageLink($templateReference)"])
177 </span>
178 </dd>
179 <dt>
180 <label for="updateClassSheet">
181 <input type="checkbox" id="updateClassSheet" name="updateClassSheet"
182 #if ($sheetReference)checked="checked" #{else}disabled="disabled" #end/>
183 $services.localization.render('platform.appwithinminutes.classEditorUpdateSheetLabel')
184 </label>
185 </dt>
186 <dd>
187 #if ($sheetReference)
188 <span class="xHint">
189 $services.localization.render('platform.appwithinminutes.classEditorUpdateSheetHint',
190 ["#pageLink($sheetReference)"])
191 </span>
192 #else
193 #inlineWarning($services.localization.render('platform.appwithinminutes.classEditorMultipleSheetsWarning'))
194 #end
195 </dd>
196 <dt>
197 <label for="updateClassTranslations">
198 <input type="checkbox" id="updateClassTranslations" name="updateClassTranslations" checked="checked" />
199 $services.localization.render('platform.appwithinminutes.classEditorUpdateTranslationsLabel')
200 </label>
201 </dt>
202 <dd>
203 <span class="xHint">
204 $services.localization.render('platform.appwithinminutes.classEditorUpdateTranslationsHint',
205 ["#pageLink($translationsReference)"])
206 </span>
207 </dd>
208 </dl>
209 #end
210
211 #macro (pageLink $reference)
212 #set ($class = 'wikilink')
213 #set ($action = 'view')
214 #set ($params = {})
215 #if (!$xwiki.exists($reference))
216 #set ($class = 'wikicreatelink')
217 #set ($action = 'create')
218 #set ($discard = $params.put('parent', $doc.fullName))
219 #end
220 <span class="$class"><a href="$escapetool.xml($xwiki.getURL($reference, $action, $escapetool.url($params)))"
221 >$escapetool.xml($reference.name)</a></span>##
222 #end
223
224 #**
225 * Display a form field.
226 *#
227 #macro (displayField $field $formFieldDoc)
228 #if ($formFieldDoc.getObject('XWiki.StyleSheetExtension'))
229 #set ($discard = $xwiki.ssx.use($formFieldDoc.fullName))
230 #end
231 #if ($formFieldDoc.getObject('XWiki.JavaScriptExtension'))
232 #set ($discard = $xwiki.jsx.use($formFieldDoc.fullName))
233 #end
234 <div class="hidden">
235 #displayFieldMetaData($field)
236 ## We need this information to avoid querying and loading all FormField documents twice.
237 ## NOTE: We use a different ID format to avoid collisions with the field meta properties.
238 <input type="hidden" id="template-$field.name" name="template-$field.name"
239 value="$escapetool.xml($formFieldDoc.fullName)"
240 data-propertyName="$escapetool.xml($formFieldDoc.getxWikiClass().propertyNames[0])" />
241 </div>
242 #set ($className = $stringtool.removeEnd($doc.fullName, 'Class'))
243 #set ($templateRef = $services.model.resolveDocument("${className}Template"))
244 #set ($templateDoc = $xwiki.getDocument($templateRef))
245 ## Simulate the editing of the class instance from the template document.
246 ## Note that we can't simply call display on the template document because $field could be a new field that hasn't
247 ## been added to the class yet (so the object from the template doesn't have this field yet).
248 <dl class="field-viewer">
249 #displayFieldProperty($field "${doc.fullName}_0_" $templateDoc.getObject($doc.fullName, true))
250 </dl>
251 #set ($propertyNames = ['name', 'prettyName', 'number', 'required', 'hint'])
252 #set ($formFieldObj = $formFieldDoc.getObject('AppWithinMinutes.FormFieldClass'))
253 #set ($customPropertyNames = $formFieldObj.getProperty('properties').value.split('\s+'))
254 #set ($discard = $customPropertyNames.removeAll($propertyNames))
255 #set ($discard = $propertyNames.addAll($customPropertyNames.subList(0, $customPropertyNames.size())))
256 <dl class="field-config">
257 #foreach ($propertyName in $propertyNames)
258 #set ($propertyDefinition = $field.xWikiClass.get($propertyName))
259 #if ($propertyDefinition)
260 #displayFieldProperty($propertyDefinition "field-${field.name}_" $field)
261 #end
262 #end
263 </dl>
264 #end
265
266 #**
267 * Display the field meta data. This is needed to preserve the field when its type is not supported by the editor.
268 *#
269 #macro (displayFieldMetaData $field)
270 <input type="hidden" id="type-$field.name" name="type-$field.name" value="$field.classType" />
271 #end
272
273 #**
274 * Displays a configuration property of a class field. This macro can also be used to display a property of an object.
275 *#
276 #macro (displayFieldProperty $property $prefix $field)
277 ## This 'displayFormType' property only exists for boolean fields.
278 #set ($displayFormType = $property.getProperty('displayFormType'))
279 #if ($property.classType == 'Boolean' && (!$displayFormType || $displayFormType.value == 'checkbox'))
280 <dt>
281 <label for="$!{prefix}$property.name">
282 #displayPropertyEditInput($property, $prefix, $field)$escapetool.xml($property.prettyName)
283 </label>
284 </dt>
285 <dd></dd>
286 #else
287 <dt><label for="${prefix}$property.name">$escapetool.xml($property.prettyName)</label></dt>
288 <dd>#displayPropertyEditInput($property, $prefix, $field)</dd>
289 #end
290 #end
291
292 #**
293 * Displays the input used to edit the specified property of the given object. The given object can be either an
294 * instance of an XWiki class or a class field. In the first case the property represents an object field and in the
295 * second case the property represents a field meta property. We currently don't use custom display for metaproperty,
296 * so in that case we fallback on displayEdit.
297 *#
298 #macro (displayPropertyEditInput $property $prefix $object)
299 #set ($wrappedProperty = $property.propertyClass)
300 #if ($wrappedProperty.isCustomDisplayed($xcontext.context))
301 #set ($customDisplayer = $!xcontext.get('propertyCustomDisplayer').display($property, $prefix, $object))
302 #if ((! $customDisplayer) && ("$!customDisplayer" == ""))
303 $doc.displayEdit($property, $prefix, $object)
304 #else
305 $customDisplayer
306 #end
307 #else
308 $doc.displayEdit($property, $prefix, $object)
309 #end
310 #end
311
312 #**
313 * Called when a new form field is added via AJAX.
314 *#
315 #macro (displayNewField)
316 ## Output the SkinExtension hooks to allow field displayers to pull JavaScript/CSS resources.
317 ## Output also the LinkExtension hook because $xwiki.linkx.use() is used to load CSS files from WebJars.
318 ## The class editor moves this resource includes in the HTML page head.
319 <!-- com.xpn.xwiki.plugin.skinx.LinkExtensionPlugin -->
320 #skinExtensionHooks
321 #set ($formFieldDoc = $xwiki.getDocument($request.field))
322 #set ($formFieldDocClassFields = $formFieldDoc.getxWikiClass().getXWikiClass().properties)
323 #if ($formFieldDocClassFields.size() > 0)
324 ## Clone the field template.
325 #set ($field = $formFieldDocClassFields.get(0).clone())
326 #if ("$!field.prettyName" == '')
327 #set ($discard = $field.setPrettyName($formFieldDoc.title))
328 #end
329 #set ($xclass = $doc.getxWikiClass().getXWikiClass())
330 #set ($discard = $xclass.addField($field.name, $field))
331 #set ($discard = $field.setObject($xclass))
332 ## Set the class document author to the current user so that customDisplay code is rendered with the current user's
333 ## rights, not the class document author's rights.
334 #set ($discard = $doc.document.authors.setEffectiveMetadataAuthor($services.user.currentUserReference))
335 #displayField($doc.getxWikiClass().get($field.name) $formFieldDoc)
336 #else
337 Unsupported form field.
338 #end
339 #end
340
341 #**
342 * Preview a class field (requires Programming Right).
343 *#
344 #macro (previewField)
345 ## Find the request parameter that specifies the field template.
346 #foreach ($paramName in $request.getParameterMap().keySet())
347 #if ($paramName.startsWith('template-'))
348 #set ($fieldName = $paramName.substring(9))
349 #set ($fieldTemplateDoc = $xwiki.getDocument($request.getParameter($paramName)))
350 #break
351 #end
352 #end
353 ##
354 ## Clone the field template.
355 #set ($field = $fieldTemplateDoc.getxWikiClass().getXWikiClass().properties.get(0).clone())
356 ##
357 ## Update the field meta properties based on the submitted data.
358 #set ($valuesFromRequest = $xcontext.context.getForm().getObject("field-$fieldName"))
359 #set ($discard = $field.getxWikiClass().fromMap($valuesFromRequest, $field))
360 ##
361 ## Don't rename the field (ignore the submitted name).
362 #set ($discard = $field.setName($fieldName))
363 ##
364 ## We have to add the field to the class before setting its value.
365 ## (otherwise the field value from the request is ignored).
366 #set ($xclass = $doc.getxWikiClass().getXWikiClass())
367 #set ($discard = $xclass.addField($fieldName, $field))
368 #set ($discard = $field.setObject($xclass))
369 ##
370 ## Create an object that has this field and set its value from request.
371 #set ($object = $fieldTemplateDoc.getObject($doc.fullName, true))
372 ##
373 ## Filter empty values from the request, otherwise the update method could try to select an invalid value.
374 #set ($values = [])
375 #foreach ($value in $request.getParameterValues("${doc.fullName}_0_$fieldName"))
376 #if ($value != '')
377 #set ($discard = $values.add($value))
378 #end
379 #end
380 #if ($values.size() > 0)
381 #set ($stringArray = $request.getParameterValues("template-$fieldName"))
382 #set ($discard = $xclass.fromMap({$fieldName: $values.toArray($stringArray)}, $object.getXWikiObject()))
383 #end
384 ##
385 ## Display the field.
386 #set ($field = $doc.getxWikiClass().get($fieldName))
387 ## Set the class document author to the current user so that customDisplay code is rendered with the current user's
388 ## rights, not the class document author's rights.
389 #set ($discard = $doc.document.authors.setEffectiveMetadataAuthor($services.user.currentUserReference))
390 #displayPropertyEditInput($field, "${doc.fullName}_0_", $object)
391 #end
392
393 #**
394 * Display the edit class form.
395 *#
396 #macro (displayEditForm)
397 #set ($discard = $xwiki.jsx.use('AppWithinMinutes.ClassEditSheet'))
398 ## Reusable helper used to recover gracefully when a preview or field-add request is rejected because the CSRF
399 ## token expired (e.g. after a server restart).
400 #set ($discard = $xwiki.jsx.use('AppWithinMinutes.Code.CSRFTokenRefresh'))
401 #set ($discard = $xwiki.ssx.use('AppWithinMinutes.ClassEditSheet'))
402 #set ($discard = $xwiki.ssx.use('AppWithinMinutes.ClassSheetGenerator'))
403 #if ("$!request.wizard" == 'true')
404 #appWizardHeader('structure')
405 #end
406 #displayFieldPalette()
407 #displayFieldCanvas()
408 #displayClassOptions()
409 #if("$!request.wizard" == 'true')
410 #appWizardFooter('structure')
411 #end
412 <div class="clearfloats"></div>
413 #end
414
415 #**
416 * Displays either the edit class form or a new form field. The later is used when adding a new form field via AJAX.
417 *#
418 #macro (doEdit)
419 #if ("$!request.field" != '' || "$!request.preview" == 'true')
420 ## CSRF protection.
421 #if (!$services.csrf.isTokenValid($request.form_token))
422 $response.setStatus(403)
423 ## Return a fresh token (using the same JSON shape as XWikiAction#csrfTokenCheck) so that the client can recover
424 ## from an expired token (e.g. after a server restart) by refreshing it, after an explicit user confirmation,
425 ## and retrying the request. Returning the token in the response is safe because the same-origin policy prevents
426 ## a CSRF attacker from reading it.
427 $response.setContentType('application/json')
428 $jsontool.serialize({'errorType': 'CSRF', 'newToken': $services.csrf.getToken()})
429 #elseif ("$!request.field" != '')
430 #displayNewField()
431 #else
432 #previewField()
433 #end
434 #else
435 ## Make sure that only the sheet content is rendered when the class is saved using AJAX.
436 <div class="hidden">
437 <input type="hidden" name="xpage" value="plain" />
438 #if ($request.wizard == 'true')
439 ## Preserve the wizard mode.
440 <input type="hidden" name="wizard" value="true" />
441 ## Provide the URL of the next wizard step as xredirect value (used by the AJAX Save & View implementation).
442 #set ($appWizardNextStepURL = "#getNextStepURL()")
443 <input type="hidden" id="xredirect" name="xredirect" value="$escapetool.xml($appWizardNextStepURL)" />
444 #end
445 ## Compute the application title to be used as the wizard step title.
446 #getAppTitle
447 </div>
448 #displayEditForm()
449 #end
450 #end
451
452 #**
453 * Create the home page of the application code space, if it doesn't exist already.
454 *#
455 #macro (maybeCreateCodeSpace)
456 #set ($codeHomePageReference = $services.model.resolveDocument('', 'default', $doc.documentReference.parent))
457 #if (!$xwiki.exists($codeHomePageReference))
458 #set ($codeSpaceTemplate = $services.model.resolveDocument('AppWithinMinutes.CodeSpaceTemplate'))
459 #set ($copyAsJob = $services.refactoring.copyAs($codeSpaceTemplate, $codeHomePageReference))
460 #try()
461 #set ($discard = $copyAsJob.join())
462 #set ($copyAsJobStatus = $services.job.getJobStatus($copyAsJob.request.id))
463 #set ($errorMessage = $copyAsJobStatus.logTail.getFirstLogEvent('ERROR').toString())
464 #end
465 #end
466 #end
467
468 #**
469 * Updates and saves the class definition based on the submitted data.
470 *#
471 #macro(updateAndSaveClass)
472 #set($class = $doc.xWikiClass)
473 #set($xclass = $class.getXWikiClass().clone())
474 #set($xdoc = $doc.document)
475 ##
476 ## Handle new fields and field type changes.
477 ##
478 #set($fieldNames = [])
479 #foreach($paramName in $request.getParameterMap().keySet())
480 #if($paramName.startsWith('type-'))
481 #set($fieldName = $paramName.substring(5))
482 #set($fieldType = $request.getParameter($paramName))
483 #set($field = $class.get($fieldName))
484 #if(!$field || $field.classType != $fieldType)
485 #if($field)
486 ## The field type has changed. Remove the field and add a new one with the proper type.
487 #set($discard = $xclass.removeField($fieldName))
488 #end
489 ## Add a new class field with the specified type.
490 #set($fieldTemplateRef = $request.getParameter("template-$fieldName"))
491 #if("$!fieldTemplateRef" != '')
492 #set($fieldTemplateDoc = $xwiki.getDocument($fieldTemplateRef))
493 #set($field = $fieldTemplateDoc.getxWikiClass().getXWikiClass().properties.get(0).clone())
494 #set($discard = $field.setObject($xclass))
495 #set($discard = $xclass.addField($fieldName, $field))
496 #set($discard = $fieldNames.add($fieldName))
497 #set($discard = $xdoc.setMetaDataDirty(true))
498 #end
499 #else
500 #set($discard = $fieldNames.add($fieldName))
501 #end
502 #end
503 #end
504 ##
505 ## Handle deleted fields.
506 ##
507 #foreach($field in $class.properties)
508 #if(!$fieldNames.contains($field.name))
509 #set($discard = $xclass.removeField($field.name))
510 #end
511 #end
512 ##
513 ## Handle field updates.
514 ##
515 #set($fieldsToRename = {})
516 #foreach($fieldName in $xclass.propertyNames)
517 #set($field = $xclass.get($fieldName))
518 #set($valuesFromRequest = $xcontext.context.getForm().getObject("field-$fieldName"))
519 #set($discard = $field.getxWikiClass().fromMap($valuesFromRequest, $field))
520 #if($field.name.matches('^[a-zA-Z_][\w:\-\.]*$'))
521 #if($fieldName != $field.name)
522 ## The field name has changed.
523 #if($xclass.get($field.name))
524 ## There is already a field with the same name.
525 #set($errorMessage = $services.localization.render('platform.appwithinminutes.classEditorDuplicateFieldNameError', [$field.name]))
526 #break
527 #else
528 #set($discard = $xclass.removeField($fieldName))
529 #set($discard = $xclass.addField($field.name, $field))
530 #set($originalField = $class.get($fieldName))
531 #if($originalField)
532 ## This is not a new field.
533 #set($discard = $fieldsToRename.put($fieldName, $field.name))
534 #set($discard = $xclass.addPropertyForRemoval($originalField.propertyClass))
535 #end
536 #end
537 #end
538 #else
539 #set($errorMessage = $services.localization.render('propertynamenotcorrect'))
540 #break
541 #end
542 #end
543 ##
544 ## Save
545 ##
546 #if(!$errorMessage)
547 #set($discard = $xdoc.setXClass($xclass))
548 #set($discard = $xdoc.renameProperties($doc.documentReference, $fieldsToRename))
549 #set($discard = $xdoc.setHidden(true))
550 #set($discard = $xdoc.setMetaDataDirty(true))
551 #set($discard = $doc.save($services.localization.render('core.comment.updateClassProperty'), $minorEdit))
552 #end
553 ##
554 ## Handle field renames.
555 ##
556 #if(!$errorMessage && !$fieldsToRename.isEmpty())
557 ## We need to load all documents (except the class and template, which we handle below) that have objects of this class and rename their properties.
558 ## If we don`t skip the template, we can not control the behaviour of emptyIsToday for date fields, which we want to handle in #updateAndSaveTemplate only once.
559 ##
560 ## FIXME: even if it is not a good practice to have an object in the class document, it is still possible. We should handle field renames for the class document
561 ## as well. Note that there is a possibility that objects in the class' document are automatically updated. Needs checking.
562 ##
563 ## We use HQL because XWQL doesn't allow us to escape the special characters from the class name.
564 #set($instancesStatement = ', BaseObject as obj where doc.fullName = obj.name and obj.className = :className'
565 + ' and doc.fullName not in (:className, :templateName)')
566 #set($className = $stringtool.removeEnd($doc.fullName, 'Class'))
567 #set($instancesQuery = $services.query.hql($instancesStatement).bindValue('className', $doc.fullName).bindValue(
568 'templateName', "${className}Template"))
569 #foreach($instanceDocName in $instancesQuery.execute())
570 #set($instanceDoc = $xwiki.getDocument($instanceDocName))
571 #set($discard = $instanceDoc.document.renameProperties($doc.documentReference, $fieldsToRename))
572 #set($discard = $instanceDoc.save($services.localization.render('core.comment.updateClassPropertyName'), true))
573 #end
574 #end
575 #end
576
577 #**
578 * Handle Date fields that have the "Empty is today" option checked in the class edit form.
579 * See https://jira.xwiki.org/browse/XWIKI-10296
580 **#
581 #macro(handleEmptyIsTodayDateFields $templateDoc)
582 #foreach($property in $doc.xWikiClass.properties)
583 ## We check directly on the request if the user provided an empty date. We can not check from the template
584 ## document's object that we've just parsed from the request using the updateObjectFromRequest method because it
585 ## already applies the emtpyIsToday mechanism and that would not be good for us.
586 #set($newValueRequestParameterName = "${doc.fullName}_0_${property.name}")
587 #set($newDateStringValue = "$!{request.getParameter($newValueRequestParameterName)}")
588 #if($property.classType == 'Date' && $property.getValue('emptyIsToday') == 1 && $newDateStringValue == '')
589 #set($discard = $templateDoc.set($property.name, $MAGIC_DATE))
590 #end
591 #end
592 #end
593
594 #**
595 * Updates and saves the class template based on the submitted data.
596 *#
597 #macro(updateAndSaveTemplate)
598 #if(!$errorMessage && $request.updateClassTemplate)
599 #set($className = $stringtool.removeEnd($doc.fullName, 'Class'))
600 #set($templateRef = $services.model.resolveDocument("${className}Template"))
601 #set($templateDoc = $xwiki.getDocument($templateRef))
602 #set($discard = $templateDoc.setParent($doc.documentReference.name))
603 #if ($request.templateTitle)
604 #set($discard = $templateDoc.setTitle($request.templateTitle))
605 #end
606 #if ($request.templateContent)
607 #set($discard = $templateDoc.setContent($request.templateContent))
608 #end
609 ## Rename the properties of the template's object, if applicable.
610 #set($discard = $templateDoc.document.renameProperties($doc.documentReference, $fieldsToRename))
611 ## Fill the template's object with the default values from the class editor's form.
612 #set($discard = $templateDoc.updateObjectFromRequest($doc.fullName))
613 ##
614 #handleEmptyIsTodayDateFields($templateDoc)
615 #set($discard = $templateDoc.setHidden(true))
616 #set($discard = $templateDoc.save(
617 $services.localization.render('platform.appwithinminutes.classEditorTemplateSaveComment'),
618 $minorEdit))
619 #end
620 #end
621
622 #**
623 * Updates and saves the class sheet based on the submitted data.
624 *#
625 #macro(updateAndSaveSheet)
626 #if(!$errorMessage && $request.updateClassSheet)
627 #set($classSheets = $services.sheet.getClassSheets($doc))
628 #if($classSheets.isEmpty())
629 #set($className = $stringtool.removeEnd($doc.fullName, 'Class'))
630 #set($sheetReference = $services.model.resolveDocument("${className}Sheet"))
631 #set($discard = $services.sheet.bindClassSheet($doc, $sheetReference))
632 #set($discard = $doc.save($services.localization.render('platform.appwithinminutes.classEditorBindSheetSaveComment'),
633 $minorEdit))
634 #elseif($classSheets.size() == 1)
635 #set($sheetReference = $classSheets.get(0))
636 #end
637 #if($sheetReference)
638 #set($sheetDoc = $xwiki.getDocument($sheetReference))
639 #set($sheetGeneratorDoc = $xwiki.getDocument('AppWithinMinutes.ClassSheetGenerator'))
640 #set($discard = $sheetDoc.setParent($doc.documentReference.name))
641 #set($discard = $sheetDoc.setContent($doc.getRenderedContent($sheetGeneratorDoc.content,
642 $sheetGeneratorDoc.syntax.toIdString(), 'plain/1.0')))
643 ## We assume for now that the output produced by the sheet generator uses the same syntax as the code of the sheet
644 ## generator. We have to set the syntax because the default wiki syntax (used when creating new wiki pages) could
645 ## be different than the one used by the sheet generator.
646 #set($discard = $sheetDoc.setSyntax($sheetGeneratorDoc.syntax))
647 #set($discard = $sheetDoc.setHidden(true))
648 #set($discard = $sheetDoc.save($services.localization.render('platform.appwithinminutes.classEditorSheetSaveComment'),
649 $minorEdit))
650 #end
651 #end
652 #end
653
654 #**
655 * Updates and saves the class translation bundle based on the submitted data.
656 *#
657 #macro(updateAndSaveTranslations)
658 #if(!$errorMessage && $request.updateClassTranslations)
659 #set($className = $stringtool.removeEnd($doc.fullName, 'Class'))
660 #set($translationsRef = $services.model.resolveDocument("${className}Translations"))
661 #set($translationsDoc = $xwiki.getDocument($translationsRef))
662 #set($translationsObj = $translationsDoc.getObject('XWiki.TranslationDocumentClass', true))
663 #set ($scope = 'USER')
664 #if ($services.security.authorization.hasAccess('admin', $doc.documentReference.wikiReference))
665 #set ($scope = 'WIKI')
666 #end
667 #set($discard = $translationsObj.set('scope', $scope))
668 #set($discard = $translationsDoc.setParent($doc.documentReference.name))
669 #set($translationsGeneratorDoc = $xwiki.getDocument('AppWithinMinutes.ClassTranslationsGenerator'))
670 #set($discard = $translationsDoc.setContent($doc.getRenderedContent($translationsGeneratorDoc.content,
671 $translationsGeneratorDoc.syntax.toIdString(), 'plain/1.0')))
672 #set($discard = $translationsDoc.setSyntaxId('plain/1.0'))
673 #set($discard = $translationsDoc.setHidden(true))
674 #set($discard = $translationsDoc.save(
675 $services.localization.render('platform.appwithinminutes.classEditorTranslationsSaveComment'),
676 $minorEdit))
677 #end
678 #end
679
680 #**
681 * Prints the URL of the next wizard step.
682 *#
683 #macro (getNextStepURL)
684 #set ($className = $stringtool.removeEnd($doc.fullName, 'Class'))
685 #set ($templateProviderReference = $services.model.resolveDocument("${className}TemplateProvider"))
686 #set ($queryString = {
687 'wizard': true,
688 'sheet': 'AppWithinMinutes.TemplateProviderEditSheet'
689 })
690 #if (!$xwiki.exists($templateProviderReference))
691 #set ($discard = $queryString.putAll({
692 'form_token': $services.csrf.getToken(),
693 'template': 'XWiki.TemplateProviderTemplate',
694 'parent': $doc.fullName
695 }))
696 #end
697 $xwiki.getURL($templateProviderReference, 'edit', $escapetool.url($queryString))##
698 #end
699
700 #**
701 * Updates and saves the class definition, the class sheet and the class template.
702 *#
703 #macro (doSave)
704 #set ($minorEdit = "$!request.minorEdit" != '')
705 #maybeCreateCodeSpace
706 #updateAndSaveClass
707 #updateAndSaveTemplate
708 #updateAndSaveSheet
709 #updateAndSaveTranslations
710 #if ($action == 'save')
711 #if ($request.getHeader('X-Requested-With') == 'XMLHttpRequest')
712 ## When saving through AJAX, don't redirect and don't render an error page. Let the client-side handle both.
713 #if ($errorMessage)
714 $response.setStatus(400)
715 #rawResponse($errorMessage, 'text/plain')
716 #else
717 $response.setStatus(204)
718 #end
719 #elseif ($errorMessage)
720 #error($errorMessage)
721 #elseif ("$!request.wizard" == 'true')
722 ## Redirect to next wizard step.
723 $response.sendRedirect("#getNextStepURL()")
724 #else
725 ## Redirect to view mode.
726 $response.sendRedirect($doc.getURL())
727 #end
728 #else
729 #if ($errorMessage)
730 $response.setStatus(400)
731 #rawResponse($errorMessage, 'text/plain')
732 #else
733 $response.setStatus(204)
734 #end
735 #end
736 #end
737 {{/velocity}}
738
739 {{velocity}}
740 #if("$!request.wizard" == 'true')
741 {{include reference="AppWithinMinutes.WizardStep" /}}
742 #end
743 {{/velocity}}
744
745 {{velocity}}
746 {{html clean="false"}}
747 ## Determine the action button that triggered the request
748 #set ($action = 'edit')
749 #foreach ($paramName in $request.getParameterMap().keySet())
750 #if ($paramName.startsWith('xaction_'))
751 #set ($action = $paramName.substring(8))
752 #break
753 #end
754 #end
755 #if ($action == 'edit')
756 #doEdit()
757 #elseif ($action == 'save' || $action == 'saveandcontinue')
758 #if ($services.csrf.isTokenValid($request.form_token))
759 #doSave()
760 #else
761 $response.sendRedirect($services.csrf.getResubmissionURL())
762 #end
763 #end
764 {{/html}}
765 {{/velocity}}