Wiki source code of ClassEditSheet

Last modified by leeb chi on 2020/05/13, 02:15

Show last authors
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">$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='$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 'field': $formFieldDoc.fullName,
101 'xeditmode': 'text'
102 })))
103 <input type="hidden" value="$fieldURL" class="data"/>
104 </li>
105 #end
106 </ul>
107 </li>
108 #end
109 </ul>
110 </div>
111 #end
112
113 #**
114 * Displays the field canvas.
115 *#
116 #macro (displayFieldCanvas)
117 #set ($propertyType2FormField = {})
118 #foreach ($formFieldDoc in $formFieldDocs)
119 ## Use the type of the field template.
120 #set ($type = $formFieldDoc.getxWikiClass().properties.get(0).classType)
121 #set ($discard = $propertyType2FormField.put($type, $formFieldDoc))
122 #end
123 <div id="canvas">
124 <p class="hint">
125 $services.localization.render('platform.appwithinminutes.classEditorCanvasHint')
126 </p>
127 <ul>
128 #set ($unknownFields = [])
129 #foreach ($field in $doc.getxWikiClass().properties)
130 #set ($formFieldDoc = $propertyType2FormField.get($field.classType))
131 #if ($formFieldDoc)
132 <li>#displayField($field $formFieldDoc)</li>
133 #else
134 #set($discard = $unknownFields.add($field))
135 #end
136 #end
137 </ul>
138 <div class="hidden">
139 ## Output the field meta data even if the field is not supported to preserve it when the class is saved.
140 #foreach ($field in $unknownFields)
141 #displayFieldMetaData($field)
142 #end
143 </div>
144 </div>
145 #end
146
147 #**
148 * Display the options to create/update the class template, the class sheet and the class translation bundle.
149 *#
150 #macro (displayClassOptions)
151 #set ($className = $stringtool.removeEnd($doc.fullName, 'Class'))
152 #set ($templateReference = $services.model.resolveDocument("${className}Template"))
153 #set ($translationsReference = $services.model.resolveDocument("${className}Translations"))
154 #set ($classSheets = $services.sheet.getClassSheets($doc))
155 #set ($sheetReference = $null)
156 #if ($classSheets.isEmpty())
157 #set ($sheetReference = $services.model.resolveDocument("${className}Sheet"))
158 #elseif ($classSheets.size() == 1)
159 #set ($sheetReference = $classSheets.get(0))
160 #end
161 ## Hide the options if neither the sheet nor the template nor the translation bundle exists. They don't have to be
162 ## updated, they have to be created.
163 <dl id="options" #if (!$xwiki.exists($sheetReference) && !$xwiki.exists($templateReference)
164 && !$xwiki.exists($translationsReference))class="hidden"#end>
165 <dt>
166 <label for="updateClassTemplate">
167 <input type="checkbox" id="updateClassTemplate" name="updateClassTemplate" checked="checked" />
168 $services.localization.render('platform.appwithinminutes.classEditorUpdateTemplateLabel')
169 </label>
170 </dt>
171 <dd>
172 <span class="xHint">
173 $services.localization.render('platform.appwithinminutes.classEditorUpdateTemplateHint',
174 ["#pageLink($templateReference)"])
175 </span>
176 </dd>
177 <dt>
178 <label for="updateClassSheet">
179 <input type="checkbox" id="updateClassSheet" name="updateClassSheet"
180 #if ($sheetReference)checked="checked" #{else}disabled="disabled" #end/>
181 $services.localization.render('platform.appwithinminutes.classEditorUpdateSheetLabel')
182 </label>
183 </dt>
184 <dd>
185 #if ($sheetReference)
186 <span class="xHint">
187 $services.localization.render('platform.appwithinminutes.classEditorUpdateSheetHint',
188 ["#pageLink($sheetReference)"])
189 </span>
190 #else
191 <span class="warningmessage">
192 $services.localization.render('platform.appwithinminutes.classEditorMultipleSheetsWarning')
193 </span>
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 #set ($displayFormType = $property.getProperty('displayFormType'))
278 #if ($property.classType == 'Boolean' && (!$displayFormType || $displayFormType.value == 'checkbox'))
279 <dt>
280 <label for="$!{prefix}$property.name">
281 #displayPropertyEditInput($property, $prefix, $field)$escapetool.xml($property.prettyName)
282 </label>
283 </dt>
284 <dd></dd>
285 #else
286 <dt><label for="${prefix}$property.name">$escapetool.xml($property.prettyName)</label></dt>
287 <dd>#displayPropertyEditInput($property, $prefix, $field)</dd>
288 #end
289 #end
290
291 #**
292 * Displays the input used to edit the specified property of the given object. The given object can be either an
293 * instance of an XWiki class or a class field. In the first case the property represents an object field and in the
294 * second case the property represents a field meta property. We currently don't use custom display for metaproperty,
295 * so in that case we fallback on displayEdit.
296 *#
297 #macro (displayPropertyEditInput $property $prefix $object)
298 #set ($wrappedProperty = $property.propertyClass)
299 #if ($wrappedProperty.isCustomDisplayed($xcontext.context))
300 #set ($customDisplayer = $!xcontext.get('propertyCustomDisplayer').display($property, $prefix, $object))
301 #if ((! $customDisplayer) && ("$!customDisplayer" == ""))
302 $doc.displayEdit($property, $prefix, $object)
303 #else
304 $customDisplayer
305 #end
306 #else
307 $doc.displayEdit($property, $prefix, $object)
308 #end
309 #end
310
311 #**
312 * Called when a new form field is added via AJAX.
313 *#
314 #macro (displayNewField)
315 ## Output the SkinExtension hooks to allow field displayers to pull JavaScript/CSS resources.
316 ## Output also the LinkExtension hook because $xwiki.linkx.use() is used to load CSS files from WebJars.
317 ## The class editor moves this resource includes in the HTML page head.
318 <!-- com.xpn.xwiki.plugin.skinx.LinkExtensionPlugin -->
319 #skinExtensionHooks
320 #set ($formFieldDoc = $xwiki.getDocument($request.field))
321 #set ($formFieldDocClassFields = $formFieldDoc.getxWikiClass().getXWikiClass().properties)
322 #if ($formFieldDocClassFields.size() > 0)
323 ## Clone the field template.
324 #set ($field = $formFieldDocClassFields.get(0).clone())
325 #if ("$!field.prettyName" == '')
326 #set ($discard = $field.setPrettyName($formFieldDoc.title))
327 #end
328 #set ($xclass = $doc.getxWikiClass().getXWikiClass())
329 #set ($discard = $xclass.addField($field.name, $field))
330 #set ($discard = $field.setObject($xclass))
331 #displayField($doc.getxWikiClass().get($field.name) $formFieldDoc)
332 #else
333 Unsupported form field.
334 #end
335 #end
336
337 #**
338 * Preview a class field (requires Programming Right).
339 *#
340 #macro (previewField)
341 ## Find the request parameter that specifies the field template.
342 #foreach ($paramName in $request.getParameterMap().keySet())
343 #if ($paramName.startsWith('template-'))
344 #set ($fieldName = $paramName.substring(9))
345 #set ($fieldTemplateDoc = $xwiki.getDocument($request.getParameter($paramName)))
346 #break
347 #end
348 #end
349 ##
350 ## Clone the field template.
351 #set ($field = $fieldTemplateDoc.getxWikiClass().getXWikiClass().properties.get(0).clone())
352 ##
353 ## Update the field meta properties based on the submitted data.
354 #set ($valuesFromRequest = $xcontext.context.getForm().getObject("field-$fieldName"))
355 #set ($discard = $field.getxWikiClass().fromMap($valuesFromRequest, $field))
356 ##
357 ## Don't rename the field (ignore the submitted name).
358 #set ($discard = $field.setName($fieldName))
359 ##
360 ## We have to add the field to the class before setting its value.
361 ## (otherwise the field value from the request is ignored).
362 #set ($xclass = $doc.getxWikiClass().getXWikiClass())
363 #set ($discard = $xclass.addField($fieldName, $field))
364 #set ($discard = $field.setObject($xclass))
365 ##
366 ## Create an object that has this field and set its value from request.
367 #set ($object = $fieldTemplateDoc.getObject($doc.fullName, true))
368 ##
369 ## Filter empty values from the request, otherwise the update method could try to select an invalid value.
370 #set ($values = [])
371 #foreach ($value in $request.getParameterValues("${doc.fullName}_0_$fieldName"))
372 #if ($value != '')
373 #set ($discard = $values.add($value))
374 #end
375 #end
376 #if ($values.size() > 0)
377 #set ($stringArray = $request.getParameterValues("template-$fieldName"))
378 #set ($discard = $xclass.fromMap({$fieldName: $values.toArray($stringArray)}, $object.getXWikiObject()))
379 #end
380 ##
381 ## Display the field.
382 #set ($field = $doc.getxWikiClass().get($fieldName))
383 #displayPropertyEditInput($field, "${doc.fullName}_0_", $object)
384 #end
385
386 #**
387 * Display the edit class form.
388 *#
389 #macro (displayEditForm)
390 #set ($discard = $xwiki.jsfx.use('js/scriptaculous/dragdrop.js'))
391 #set ($discard = $xwiki.jsx.use('AppWithinMinutes.ClassEditSheet'))
392 #set ($discard = $xwiki.ssx.use('AppWithinMinutes.ClassEditSheet'))
393 #set ($discard = $xwiki.ssx.use('AppWithinMinutes.ClassSheetGenerator'))
394 #if ("$!request.wizard" == 'true')
395 #appWizardHeader('structure')
396 #end
397 #displayFieldPalette()
398 #displayFieldCanvas()
399 #displayClassOptions()
400 #if("$!request.wizard" == 'true')
401 #appWizardFooter('structure')
402 #end
403 <div class="clearfloats"></div>
404 #end
405
406 #**
407 * Displays either the edit class form or a new form field. The later is used when adding a new form field via AJAX.
408 *#
409 #macro (doEdit)
410 #if ("$!request.field" != '')
411 #displayNewField()
412 #elseif ("$!request.preview" == 'true')
413 #previewField()
414 #else
415 ## Make sure that only the sheet content is rendered when the class is saved using AJAX.
416 <div class="hidden">
417 <input type="hidden" name="xpage" value="plain" />
418 #if ($request.wizard == 'true')
419 ## Preserve the wizard mode.
420 <input type="hidden" name="wizard" value="true" />
421 #end
422 ## Compute the application title to be used as the wizard step title.
423 #getAppTitle
424 </div>
425 #displayEditForm()
426 #end
427 #end
428
429 #**
430 * Create the home page of the application code space, if it doesn't exist already.
431 *#
432 #macro (maybeCreateCodeSpace)
433 #set ($codeHomePageReference = $services.model.resolveDocument('', 'default', $doc.documentReference.parent))
434 #if (!$xwiki.exists($codeHomePageReference))
435 #set ($codeSpaceTemplate = $services.model.resolveDocument('AppWithinMinutes.CodeSpaceTemplate'))
436 #set ($copyAsJob = $services.refactoring.copyAs($codeSpaceTemplate, $codeHomePageReference))
437 #try()
438 #set ($discard = $copyAsJob.join())
439 #set ($copyAsJobStatus = $services.job.getJobStatus($copyAsJob.request.id))
440 #set ($errorMessage = $copyAsJobStatus.logTail.getFirstLogEvent('ERROR').toString())
441 #end
442 #end
443 #end
444
445 #**
446 * Updates and saves the class definition based on the submitted data.
447 *#
448 #macro(updateAndSaveClass)
449 #set($class = $doc.xWikiClass)
450 #set($xclass = $class.getXWikiClass().clone())
451 #set($xdoc = $doc.document)
452 ##
453 ## Handle new fields and field type changes.
454 ##
455 #set($fieldNames = [])
456 #foreach($paramName in $request.getParameterMap().keySet())
457 #if($paramName.startsWith('type-'))
458 #set($fieldName = $paramName.substring(5))
459 #set($fieldType = $request.getParameter($paramName))
460 #set($field = $class.get($fieldName))
461 #if(!$field || $field.classType != $fieldType)
462 #if($field)
463 ## The field type has changed. Remove the field and add a new one with the proper type.
464 #set($discard = $xclass.removeField($fieldName))
465 #end
466 ## Add a new class field with the specified type.
467 #set($fieldTemplateRef = $request.getParameter("template-$fieldName"))
468 #if("$!fieldTemplateRef" != '')
469 #set($fieldTemplateDoc = $xwiki.getDocument($fieldTemplateRef))
470 #set($field = $fieldTemplateDoc.getxWikiClass().getXWikiClass().properties.get(0).clone())
471 #set($discard = $field.setObject($xclass))
472 #set($discard = $xclass.addField($fieldName, $field))
473 #set($discard = $fieldNames.add($fieldName))
474 #set($discard = $xdoc.setMetaDataDirty(true))
475 #end
476 #else
477 #set($discard = $fieldNames.add($fieldName))
478 #end
479 #end
480 #end
481 ##
482 ## Handle deleted fields.
483 ##
484 #foreach($field in $class.properties)
485 #if(!$fieldNames.contains($field.name))
486 #set($discard = $xclass.removeField($field.name))
487 #end
488 #end
489 ##
490 ## Handle field updates.
491 ##
492 #set($fieldsToRename = {})
493 #foreach($fieldName in $xclass.propertyNames)
494 #set($field = $xclass.get($fieldName))
495 #set($valuesFromRequest = $xcontext.context.getForm().getObject("field-$fieldName"))
496 #set($discard = $field.getxWikiClass().fromMap($valuesFromRequest, $field))
497 #if($field.name.matches('^[a-zA-Z_][\w:\-\.]*$'))
498 #if($fieldName != $field.name)
499 ## The field name has changed.
500 #if($xclass.get($field.name))
501 ## There is already a field with the same name.
502 #set($errorMessage = $services.localization.render('platform.appwithinminutes.classEditorDuplicateFieldNameError', [$field.name]))
503 #break
504 #else
505 #set($discard = $xclass.removeField($fieldName))
506 #set($discard = $xclass.addField($field.name, $field))
507 #set($originalField = $class.get($fieldName))
508 #if($originalField)
509 ## This is not a new field.
510 #set($discard = $fieldsToRename.put($fieldName, $field.name))
511 #set($discard = $xclass.addPropertyForRemoval($originalField.propertyClass))
512 #end
513 #end
514 #end
515 #else
516 #set($errorMessage = $services.localization.render('propertynamenotcorrect'))
517 #break
518 #end
519 #end
520 ##
521 ## Save
522 ##
523 #if(!$errorMessage)
524 #set($discard = $xdoc.setXClass($xclass))
525 #set($discard = $xdoc.renameProperties($doc.documentReference, $fieldsToRename))
526 #set($discard = $xdoc.setHidden(true))
527 #set($discard = $xdoc.setMetaDataDirty(true))
528 #set($discard = $doc.save($services.localization.render('core.comment.updateClassProperty'), $minorEdit))
529 #end
530 ##
531 ## Handle field renames.
532 ##
533 #if(!$errorMessage && !$fieldsToRename.isEmpty())
534 ## 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.
535 ## 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.
536 ##
537 ## 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
538 ## as well. Note that there is a possibility that objects in the class' document are automatically updated. Needs checking.
539 ##
540 ## We use HQL because XWQL doesn't allow us to escape the special characters from the class name.
541 #set($instancesStatement = ', BaseObject as obj where doc.fullName = obj.name and obj.className = :className'
542 + ' and doc.fullName not in (:className, :templateName)')
543 #set($className = $stringtool.removeEnd($doc.fullName, 'Class'))
544 #set($instancesQuery = $services.query.hql($instancesStatement).bindValue('className', $doc.fullName).bindValue(
545 'templateName', "${className}Template"))
546 #foreach($instanceDocName in $instancesQuery.execute())
547 #set($instanceDoc = $xwiki.getDocument($instanceDocName))
548 #set($discard = $instanceDoc.document.renameProperties($doc.documentReference, $fieldsToRename))
549 #set($discard = $instanceDoc.save($services.localization.render('core.comment.updateClassPropertyName'), true))
550 #end
551 #end
552 #end
553
554 #**
555 * Handle Date fields that have the "Empty is today" option checked in the class edit form.
556 * See https://jira.xwiki.org/browse/XWIKI-10296
557 **#
558 #macro(handleEmptyIsTodayDateFields $templateDoc)
559 #foreach($property in $doc.xWikiClass.properties)
560 ## We check directly on the request if the user provided an empty date. We can not check from the template
561 ## document's object that we've just parsed from the request using the updateObjectFromRequest method because it
562 ## already applies the emtpyIsToday mechanism and that would not be good for us.
563 #set($newValueRequestParameterName = "${doc.fullName}_0_${property.name}")
564 #set($newDateStringValue = "$!{request.getParameter($newValueRequestParameterName)}")
565 #if($property.classType == 'Date' && $property.getValue('emptyIsToday') == 1 && $newDateStringValue == '')
566 #set($discard = $templateDoc.set($property.name, $MAGIC_DATE))
567 #end
568 #end
569 #end
570
571 #**
572 * Updates and saves the class template based on the submitted data.
573 *#
574 #macro(updateAndSaveTemplate)
575 #if(!$errorMessage && $request.updateClassTemplate)
576 #set($className = $stringtool.removeEnd($doc.fullName, 'Class'))
577 #set($templateRef = $services.model.resolveDocument("${className}Template"))
578 #set($templateDoc = $xwiki.getDocument($templateRef))
579 #set($discard = $templateDoc.setParent($doc.documentReference.name))
580 #if ($request.templateTitle)
581 #set($discard = $templateDoc.setTitle($request.templateTitle))
582 #end
583 #if ($request.templateContent)
584 #set($discard = $templateDoc.setContent($request.templateContent))
585 #end
586 ## Rename the properties of the template's object, if applicable.
587 #set($discard = $templateDoc.document.renameProperties($doc.documentReference, $fieldsToRename))
588 ## Fill the template's object with the default values from the class editor's form.
589 #set($discard = $templateDoc.updateObjectFromRequest($doc.fullName))
590 ##
591 #handleEmptyIsTodayDateFields($templateDoc)
592 #set($discard = $templateDoc.setHidden(true))
593 #set($discard = $templateDoc.save(
594 $services.localization.render('platform.appwithinminutes.classEditorTemplateSaveComment'),
595 $minorEdit))
596 #end
597 #end
598
599 #**
600 * Updates and saves the class sheet based on the submitted data.
601 *#
602 #macro(updateAndSaveSheet)
603 #if(!$errorMessage && $request.updateClassSheet)
604 #set($classSheets = $services.sheet.getClassSheets($doc))
605 #if($classSheets.isEmpty())
606 #set($className = $stringtool.removeEnd($doc.fullName, 'Class'))
607 #set($sheetReference = $services.model.resolveDocument("${className}Sheet"))
608 #set($discard = $services.sheet.bindClassSheet($doc, $sheetReference))
609 #set($discard = $doc.save($services.localization.render('platform.appwithinminutes.classEditorBindSheetSaveComment'),
610 $minorEdit))
611 #elseif($classSheets.size() == 1)
612 #set($sheetReference = $classSheets.get(0))
613 #end
614 #if($sheetReference)
615 #set($sheetDoc = $xwiki.getDocument($sheetReference))
616 #set($sheetGeneratorDoc = $xwiki.getDocument('AppWithinMinutes.ClassSheetGenerator'))
617 #set($discard = $sheetDoc.setParent($doc.documentReference.name))
618 #set($discard = $sheetDoc.setContent($doc.getRenderedContent($sheetGeneratorDoc.content,
619 $sheetGeneratorDoc.syntax.toIdString(), 'plain/1.0')))
620 #set($discard = $sheetDoc.setHidden(true))
621 #set($discard = $sheetDoc.save($services.localization.render('platform.appwithinminutes.classEditorSheetSaveComment'),
622 $minorEdit))
623 #end
624 #end
625 #end
626
627 #**
628 * Updates and saves the class translation bundle based on the submitted data.
629 *#
630 #macro(updateAndSaveTranslations)
631 #if(!$errorMessage && $request.updateClassTranslations)
632 #set($className = $stringtool.removeEnd($doc.fullName, 'Class'))
633 #set($translationsRef = $services.model.resolveDocument("${className}Translations"))
634 #set($translationsDoc = $xwiki.getDocument($translationsRef))
635 #set($translationsObj = $translationsDoc.getObject('XWiki.TranslationDocumentClass', true))
636 #set ($scope = 'USER')
637 #if ($services.security.authorization.hasAccess('admin', $doc.documentReference.wikiReference))
638 #set ($scope = 'WIKI')
639 #end
640 #set($discard = $translationsObj.set('scope', $scope))
641 #set($discard = $translationsDoc.setParent($doc.documentReference.name))
642 #set($translationsGeneratorDoc = $xwiki.getDocument('AppWithinMinutes.ClassTranslationsGenerator'))
643 #set($discard = $translationsDoc.setContent($doc.getRenderedContent($translationsGeneratorDoc.content,
644 $translationsGeneratorDoc.syntax.toIdString(), 'plain/1.0')))
645 #set($discard = $translationsDoc.setHidden(true))
646 #set($discard = $translationsDoc.save(
647 $services.localization.render('platform.appwithinminutes.classEditorTranslationsSaveComment'),
648 $minorEdit))
649 #end
650 #end
651
652 #**
653 * Updates and saves the class definition, the class sheet and the class template.
654 *#
655 #macro (doSave)
656 #set ($minorEdit = "$!request.minorEdit" != '')
657 #maybeCreateCodeSpace
658 #updateAndSaveClass
659 #updateAndSaveTemplate
660 #updateAndSaveSheet
661 #updateAndSaveTranslations
662 #if ($action == 'save')
663 #if ($errorMessage)
664 <div class="box errormessage">$errorMessage</div>
665 #elseif ("$!request.wizard" == 'true')
666 ## Redirect to next wizard step.
667 #set ($className = $stringtool.removeEnd($doc.fullName, 'Class'))
668 #set ($templateProviderReference = $services.model.resolveDocument("${className}TemplateProvider"))
669 #set ($queryString = {
670 'wizard': true,
671 'sheet': 'AppWithinMinutes.TemplateProviderEditSheet'
672 })
673 #if (!$xwiki.exists($templateProviderReference))
674 #set ($discard = $queryString.putAll({
675 'template': 'XWiki.TemplateProviderTemplate',
676 'parent': $doc.fullName
677 }))
678 #end
679 $response.sendRedirect($xwiki.getURL($templateProviderReference, 'edit', $escapetool.url($queryString)))
680 #else
681 ## Redirect to view mode.
682 $response.sendRedirect($doc.getURL())
683 #end
684 #else
685 #if ($errorMessage)
686 $response.sendError(400, $errorMessage)
687 #else
688 $response.setStatus(204)
689 #end
690 #end
691 #end
692 {{/velocity}}
693
694 {{velocity}}
695 #if("$!request.wizard" == 'true')
696 {{include reference="AppWithinMinutes.WizardStep" /}}
697 #end
698 {{/velocity}}
699
700 {{velocity}}
701 {{html clean="false"}}
702 ## Determine the action button that triggered the request
703 #set ($action = 'edit')
704 #foreach ($paramName in $request.getParameterMap().keySet())
705 #if ($paramName.startsWith('xaction_'))
706 #set ($action = $paramName.substring(8))
707 #break
708 #end
709 #end
710 #if ($action == 'edit')
711 #doEdit()
712 #elseif ($action == 'save' || $action == 'saveandcontinue')
713 #if ($services.csrf.isTokenValid($request.form_token))
714 #doSave()
715 #else
716 $response.sendRedirect($services.csrf.getResubmissionURL())
717 #end
718 #end
719 {{/html}}
720 {{/velocity}}
深圳市艾拓先锋企业管理咨询有限公司