From 8ea4759f5e22a6411c961e3399468d2929c2372d Mon Sep 17 00:00:00 2001 From: srosse <none@none> Date: Thu, 1 Mar 2018 08:54:24 +0100 Subject: [PATCH] OO-3315: refactor the UI rules with some classic boolean logic --- .../coursecreation/CourseCreationHelper.java | 88 +- .../model/CourseCreationConfiguration.java | 26 +- .../steps/EnrollmentEditForm.java | 64 +- .../user/bulkChange/UserBulkChangeStep00.java | 142 +- .../flexible/DependencyRuleApplayable.java | 50 - .../form/flexible/FormItemContainer.java | 20 - .../form/flexible/FormItemDependencyRule.java | 77 - .../components/form/flexible/impl/Form.java | 131 +- .../flexible/impl/FormLayoutContainer.java | 51 +- .../flexible/impl/FormWrapperContainer.java | 19 +- .../rules/FormItemDependencyRuleImpl.java | 159 -- .../MultiSelectionTriggerdDependencyRule.java | 67 - .../flexible/impl/rules/RulesFactory.java | 273 ---- ...SingleSelectionTriggerdDependencyRule.java | 68 - .../TextElementTriggerdDependencyRule.java | 68 - .../util/i18n/ui/I18nConfigController.java | 24 +- .../ui/I18nConfigSubNewLangController.java | 49 +- .../ConditionConfigEasyController.java | 1273 +++++++---------- .../condition/_content/easycondedit.html | 37 +- .../nodes/scorm/ScormEditController.java | 85 +- ...CourseNodeDisplayConfigFormController.java | 108 +- .../nodes/st/STCourseNodeEditController.java | 10 +- .../GuiDemoFlexiFormAdvancedController.java | 64 +- .../guidemo/GuiDemoFlexiFormHideUnhide.java | 55 +- .../GuiDemoFlexiFormMainController.java | 89 +- 25 files changed, 902 insertions(+), 2195 deletions(-) delete mode 100644 src/main/java/org/olat/core/gui/components/form/flexible/DependencyRuleApplayable.java delete mode 100644 src/main/java/org/olat/core/gui/components/form/flexible/FormItemDependencyRule.java delete mode 100644 src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/FormItemDependencyRuleImpl.java delete mode 100644 src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/MultiSelectionTriggerdDependencyRule.java delete mode 100644 src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/RulesFactory.java delete mode 100644 src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/SingleSelectionTriggerdDependencyRule.java delete mode 100644 src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/TextElementTriggerdDependencyRule.java diff --git a/src/main/java/de/tuchemnitz/wizard/workflows/coursecreation/CourseCreationHelper.java b/src/main/java/de/tuchemnitz/wizard/workflows/coursecreation/CourseCreationHelper.java index 1086dea767c..64d200fae4d 100644 --- a/src/main/java/de/tuchemnitz/wizard/workflows/coursecreation/CourseCreationHelper.java +++ b/src/main/java/de/tuchemnitz/wizard/workflows/coursecreation/CourseCreationHelper.java @@ -175,7 +175,7 @@ public class CourseCreationHelper { .translate("cce.contactform.descr")); if (contactNode instanceof COCourseNode) { - final List<String> emails = new ArrayList<String>(); + final List<String> emails = new ArrayList<>(); String subject = translator.translate("cce.contactform.subject") + " " + courseConfig.getCourseTitle(); String email = ureq.getIdentity().getUser().getProperty(UserConstants.EMAIL, ureq.getLocale()); @@ -201,9 +201,8 @@ public class CourseCreationHelper { // get default context for learning groups // create n learning groups with m allowed members - String comma = ""; - String tmpGroupList = ""; - String groupNamesList = ""; + + List<Long> groupIdsList = new ArrayList<>(); for (int i = 0; i < courseConfig.getGroupCount(); i++) { // create group String name = groupBaseName + " " + (i + 1); @@ -214,62 +213,49 @@ public class CourseCreationHelper { CollaborationTools ct = CollaborationToolsFactory.getInstance().getOrCreateCollaborationTools(learningGroup); ct.setToolEnabled(CollaborationTools.TOOL_CONTACT, true); // append to current learning group list - groupNamesList = tmpGroupList + comma + learningGroup.getName(); - enCourseNode.getModuleConfiguration().set(ENCourseNode.CONFIG_GROUPNAME, groupNamesList); - if (i == 0) { - comma = ","; - } - tmpGroupList = (String) enCourseNode.getModuleConfiguration().get(ENCourseNode.CONFIG_GROUPNAME); + groupIdsList.add(learningGroup.getKey()); } + enCourseNode.getModuleConfiguration().set(ENCourseNode.CONFIG_GROUP_IDS, groupIdsList); // set signout property enCourseNode.getModuleConfiguration().set(ENCourseNode.CONF_CANCEL_ENROLL_ENABLED, courseConfig.getEnableSignout()); // access limits on chosen course elements if (courseConfig.getEnableAccessLimit()) { - if (courseConfig.isEnableAclContactForm()) { - if (contactNode instanceof COCourseNode) { - Condition c = ((COCourseNode) contactNode).getPreConditionVisibility(); - c.setEasyModeGroupAccess(groupNamesList); - ((COCourseNode) contactNode).setNoAccessExplanation(translator.translate("noaccessexplain")); - // calculate expression from easy mode form - String condString = c.getConditionFromEasyModeConfiguration(); - c.setConditionExpression(condString); - c.setExpertMode(false); - } + if (courseConfig.isEnableAclContactForm() && contactNode instanceof COCourseNode) { + Condition c = ((COCourseNode) contactNode).getPreConditionVisibility(); + c.setEasyModeGroupAccessIdList(groupIdsList); + ((COCourseNode) contactNode).setNoAccessExplanation(translator.translate("noaccessexplain")); + // calculate expression from easy mode form + String condString = c.getConditionFromEasyModeConfiguration(); + c.setConditionExpression(condString); } - if (courseConfig.isEnableAclSinglePage()) { - if (singlePageNode instanceof SPCourseNode) { - Condition c = ((SPCourseNode) singlePageNode).getPreConditionVisibility(); - c.setEasyModeGroupAccess(groupNamesList); - ((SPCourseNode) singlePageNode).setNoAccessExplanation(translator.translate("noaccessexplain")); - // calculate expression from easy mode form - String condString = c.getConditionFromEasyModeConfiguration(); - c.setConditionExpression(condString); - c.setExpertMode(false); - } + if (courseConfig.isEnableAclSinglePage() && singlePageNode instanceof SPCourseNode) { + Condition c = ((SPCourseNode) singlePageNode).getPreConditionVisibility(); + c.setEasyModeGroupAccessIdList(groupIdsList); + ((SPCourseNode) singlePageNode).setNoAccessExplanation(translator.translate("noaccessexplain")); + // calculate expression from easy mode form + String condString = c.getConditionFromEasyModeConfiguration(); + c.setConditionExpression(condString); + c.setExpertMode(false); } - if (courseConfig.isEnableAclForum()) { - if (forumNode instanceof FOCourseNode) { - Condition c = ((FOCourseNode) forumNode).getPreConditionVisibility(); - c.setEasyModeGroupAccess(groupNamesList); - ((FOCourseNode) forumNode).setNoAccessExplanation(translator.translate("noaccessexplain")); - // calculate expression from easy mode form - String condString = c.getConditionFromEasyModeConfiguration(); - c.setConditionExpression(condString); - c.setExpertMode(false); - } + if (courseConfig.isEnableAclForum() && forumNode instanceof FOCourseNode) { + Condition c = ((FOCourseNode) forumNode).getPreConditionVisibility(); + c.setEasyModeGroupAccessIdList(groupIdsList); + ((FOCourseNode) forumNode).setNoAccessExplanation(translator.translate("noaccessexplain")); + // calculate expression from easy mode form + String condString = c.getConditionFromEasyModeConfiguration(); + c.setConditionExpression(condString); + c.setExpertMode(false); } - if (courseConfig.isEnableAclDownloadFolder()) { - if (downloadFolderNode instanceof BCCourseNode) { - Condition c = ((BCCourseNode) downloadFolderNode).getPreConditionVisibility(); - c.setEasyModeGroupAccess(groupNamesList); - ((BCCourseNode) downloadFolderNode).setNoAccessExplanation(translator.translate("noaccessexplain")); - // calculate expression from easy mode form - String condString = c.getConditionFromEasyModeConfiguration(); - c.setConditionExpression(condString); - c.setExpertMode(false); - } + if (courseConfig.isEnableAclDownloadFolder() && downloadFolderNode instanceof BCCourseNode) { + Condition c = ((BCCourseNode) downloadFolderNode).getPreConditionVisibility(); + c.setEasyModeGroupAccessIdList(groupIdsList); + ((BCCourseNode) downloadFolderNode).setNoAccessExplanation(translator.translate("noaccessexplain")); + // calculate expression from easy mode form + String condString = c.getConditionFromEasyModeConfiguration(); + c.setConditionExpression(condString); + c.setExpertMode(false); } } } @@ -316,7 +302,7 @@ public class CourseCreationHelper { final PublishProcess pp = PublishProcess.getInstance(course, cetm, ureq.getLocale()); final StatusDescription[] sds; // create publish node list - List<String> nodeIds = new ArrayList<String>(); + List<String> nodeIds = new ArrayList<>(); nodeIds.add(cetm.getRootNode().getIdent()); for (int i = 0; i < cetm.getRootNode().getChildCount(); i++) { nodeIds.add(cetm.getRootNode().getChildAt(i).getIdent()); diff --git a/src/main/java/de/tuchemnitz/wizard/workflows/coursecreation/model/CourseCreationConfiguration.java b/src/main/java/de/tuchemnitz/wizard/workflows/coursecreation/model/CourseCreationConfiguration.java index 5cfd5176fd4..65ba18cd64f 100644 --- a/src/main/java/de/tuchemnitz/wizard/workflows/coursecreation/model/CourseCreationConfiguration.java +++ b/src/main/java/de/tuchemnitz/wizard/workflows/coursecreation/model/CourseCreationConfiguration.java @@ -32,7 +32,8 @@ package de.tuchemnitz.wizard.workflows.coursecreation.model; -import org.apache.commons.io.IOUtils; +import java.io.IOException; + import org.apache.velocity.context.Context; import org.olat.core.commons.editor.htmleditor.WysiwygFactory; import org.olat.core.gui.GlobalSettings; @@ -44,6 +45,8 @@ import org.olat.core.gui.render.StringOutput; import org.olat.core.gui.render.velocity.VelocityHelper; import org.olat.core.gui.render.velocity.VelocityRenderDecorator; import org.olat.core.gui.translator.Translator; +import org.olat.core.logging.OLog; +import org.olat.core.logging.Tracing; import org.olat.course.editor.CourseAccessAndProperties; import org.olat.repository.CatalogEntry; @@ -62,6 +65,8 @@ import de.tuchemnitz.wizard.workflows.coursecreation.CourseCreationHelper; * @author Sebastian Fritzsche (seb.fritzsche@googlemail.com) */ public class CourseCreationConfiguration { + + private static final OLog log = Tracing.createLoggerFor(CourseCreationConfiguration.class); public static final String ACL_GUEST = "acl_guest"; public static final String ACL_OLAT = "acl_olat"; @@ -368,14 +373,17 @@ public class CourseCreationConfiguration { Context context = vc.getContext(); Renderer fr = Renderer.getInstance(vc, translator, null, new RenderResult(), globalSettings); - StringOutput wOut = new StringOutput(10000); - VelocityRenderDecorator vrdec = new VelocityRenderDecorator(fr, vc, wOut); - context.put("r", vrdec); - VelocityHelper.getInstance().mergeContent(vc.getPage(), context, wOut, null); - //free the decorator - context.remove("r"); - IOUtils.closeQuietly(vrdec); - return WysiwygFactory.createXHtmlFileContent(wOut.toString(), courseTitle); + try(StringOutput wOut = new StringOutput(10000); + VelocityRenderDecorator vrdec = new VelocityRenderDecorator(fr, vc, wOut)) { + context.put("r", vrdec); + VelocityHelper.getInstance().mergeContent(vc.getPage(), context, wOut, null); + //free the decorator + context.remove("r"); + return WysiwygFactory.createXHtmlFileContent(wOut.toString(), courseTitle); + } catch(IOException e) { + log.error("", e); + return null; + } } private static class EmptyAJAXFlags extends AJAXFlags { diff --git a/src/main/java/de/tuchemnitz/wizard/workflows/coursecreation/steps/EnrollmentEditForm.java b/src/main/java/de/tuchemnitz/wizard/workflows/coursecreation/steps/EnrollmentEditForm.java index c220d816789..3279c5c99ee 100644 --- a/src/main/java/de/tuchemnitz/wizard/workflows/coursecreation/steps/EnrollmentEditForm.java +++ b/src/main/java/de/tuchemnitz/wizard/workflows/coursecreation/steps/EnrollmentEditForm.java @@ -33,9 +33,8 @@ package de.tuchemnitz.wizard.workflows.coursecreation.steps; import java.util.ArrayList; -import java.util.HashSet; +import java.util.Collection; import java.util.List; -import java.util.Set; import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.form.flexible.FormItem; @@ -45,7 +44,6 @@ import org.olat.core.gui.components.form.flexible.elements.TextElement; import org.olat.core.gui.components.form.flexible.impl.FormBasicController; import org.olat.core.gui.components.form.flexible.impl.FormEvent; import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer; -import org.olat.core.gui.components.form.flexible.impl.rules.RulesFactory; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.Event; import org.olat.core.gui.control.WindowControl; @@ -77,13 +75,11 @@ public class EnrollmentEditForm extends FormBasicController { // number of members per group private TextElement subscriberCount; // list of course elements used for access limitations - private final List<String> elements = new ArrayList<String>(); - private String[] keys; - private String[] values; + private final List<String> elements = new ArrayList<>(); + private String[] keys = new String[] { "ison" }; + private String[] values = new String[] { "" }; private final CourseCreationConfiguration courseConfig; - private String SUBSCRIBER_COUNT = "25"; - /** * Standard constructor * @param ureq @@ -110,7 +106,6 @@ public class EnrollmentEditForm extends FormBasicController { if (courseConfig.isCreateDownloadFolder()) elements.add(translate("cce.downloadfolder")); if (courseConfig.isCreateForum()) elements.add(translate("cce.forum")); if (courseConfig.isCreateContactForm()) elements.add(translate("cce.contactform")); - } @Override @@ -131,18 +126,12 @@ public class EnrollmentEditForm extends FormBasicController { groupCount.setRegexMatchCheck("\\d*", "cce.enrollment.error.groupcount"); groupCount.showError(false); - - if (courseConfig.getSubscriberCount() != null) subscriberCount = uifactory.addTextElement("subscriberCount", - "en.subscribercount", 3, courseConfig.getSubscriberCount().toString(), formLayout); - else subscriberCount = uifactory.addTextElement("subscriberCount", "en.subscribercount", 3, SUBSCRIBER_COUNT, formLayout); - + String subCount = courseConfig.getSubscriberCount() == null ? "25" : courseConfig.getSubscriberCount().toString(); + subscriberCount = uifactory.addTextElement("subscriberCount", "en.subscribercount", + 3, subCount, formLayout); subscriberCount.setErrorKey("cce.enrollment.error.subscribercount", null); subscriberCount.showError(false); - - keys = new String[] { "ison" }; - values = new String[] { "" }; - accessLimit = uifactory.addCheckboxesVertical("accessLimit", formLayout, keys, values, 1); accessLimit.setLabel("en.accesscheckbox", null); accessLimit.select("ison", courseConfig.getEnableAccessLimit()); @@ -159,8 +148,7 @@ public class EnrollmentEditForm extends FormBasicController { courseElements = uifactory.addCheckboxesVertical("courseElements", formLayout, keys, values, 1); courseElements.setLabel("en.selectelements", null); - - if (!accessLimit.isSelected(0)) courseElements.setVisible(false); + courseElements.setVisible(accessLimit.isSelected(0)); // copy elements list into an array for (int i = 0; i < elements.size(); i++) { @@ -176,23 +164,15 @@ public class EnrollmentEditForm extends FormBasicController { } } - // rules to hide / unhide - Set<FormItem> targets = new HashSet<FormItem>(); - targets.add(courseElements); - RulesFactory.createHideRule(accessLimit, null, targets, formLayout); - RulesFactory.createShowRule(accessLimit, "ison", targets, formLayout); - // Buttons formLayout.add(formButtons); - uifactory.addFormSubmitButton("okButton", formButtons); uifactory.addFormCancelButton("cancelButton", formButtons, ureq, getWindowControl()); + uifactory.addFormSubmitButton("okButton", formButtons); } - - @Override protected boolean validateFormLogic(UserRequest ureq) { - boolean allOk = true; + boolean allOk = super.validateFormLogic(ureq); String groupCountStr = groupCount.getValue(); if(StringHelper.containsNonWhitespace(groupCountStr)) { @@ -207,7 +187,7 @@ public class EnrollmentEditForm extends FormBasicController { allOk &= false; } - return allOk & super.validateFormLogic(ureq); + return allOk; } @Override @@ -222,18 +202,26 @@ public class EnrollmentEditForm extends FormBasicController { if (s.length() > 0) { courseConfig.setSubscriberCount(new Integer(s)); } - courseConfig.setEnableAccessLimit(accessLimit.getSelectedKeys().size() == 1); - courseConfig.setEnableAclSinglePage(courseElements.getSelectedKeys().contains(translate("cce.informationpage"))); - courseConfig.setEnableAclContactForm(courseElements.getSelectedKeys().contains(translate("cce.contactform"))); - courseConfig.setEnableAclDownloadFolder(courseElements.getSelectedKeys().contains(translate("cce.downloadfolder"))); - courseConfig.setEnableAclForum(courseElements.getSelectedKeys().contains(translate("cce.forum"))); + courseConfig.setEnableAccessLimit(accessLimit.isAtLeastSelected(1)); + Collection<String> selectedCourseElements = courseElements.getSelectedKeys(); + courseConfig.setEnableAclSinglePage(selectedCourseElements.contains(translate("cce.informationpage"))); + courseConfig.setEnableAclContactForm(selectedCourseElements.contains(translate("cce.contactform"))); + courseConfig.setEnableAclDownloadFolder(selectedCourseElements.contains(translate("cce.downloadfolder"))); + courseConfig.setEnableAclForum(selectedCourseElements.contains(translate("cce.forum"))); fireEvent(ureq, Event.DONE_EVENT); } + @Override + protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) { + if(accessLimit == source) { + courseElements.setVisible(accessLimit.isAtLeastSelected(1)); + } + super.formInnerEvent(ureq, source, event); + } + @Override protected void formCancelled(UserRequest ureq) { fireEvent(ureq, Event.CANCELLED_EVENT); } - -} +} \ No newline at end of file diff --git a/src/main/java/org/olat/admin/user/bulkChange/UserBulkChangeStep00.java b/src/main/java/org/olat/admin/user/bulkChange/UserBulkChangeStep00.java index 72220e7b5c3..c64f603ec14 100644 --- a/src/main/java/org/olat/admin/user/bulkChange/UserBulkChangeStep00.java +++ b/src/main/java/org/olat/admin/user/bulkChange/UserBulkChangeStep00.java @@ -21,7 +21,6 @@ package org.olat.admin.user.bulkChange; import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -42,7 +41,6 @@ import org.olat.core.gui.components.form.flexible.elements.TextElement; import org.olat.core.gui.components.form.flexible.impl.Form; import org.olat.core.gui.components.form.flexible.impl.FormEvent; import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer; -import org.olat.core.gui.components.form.flexible.impl.rules.RulesFactory; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.WindowControl; import org.olat.core.gui.control.generic.wizard.BasicStep; @@ -72,8 +70,8 @@ public /** */ class UserBulkChangeStep00 extends BasicStep { - static final String usageIdentifyer = UserBulkChangeStep00.class.getCanonicalName(); - static final String usageIdentifyerForAllProperties = ProfileFormController.class.getCanonicalName(); + private final String usageIdentifyer = UserBulkChangeStep00.class.getCanonicalName(); + private final String usageIdentifyerForAllProperties = ProfileFormController.class.getCanonicalName(); private List<Identity> identitiesToEdit; private static VelocityEngine velocityEngine; private boolean isAdministrativeUser; @@ -116,25 +114,24 @@ class UserBulkChangeStep00 extends BasicStep { */ @Override public StepFormController getStepController(UserRequest ureq, WindowControl windowControl, StepsRunContext stepsRunContext, Form form) { - StepFormController stepI = new UserBulkChangeStepForm00(ureq, windowControl, form, stepsRunContext); - return stepI; + return new UserBulkChangeStepForm00(ureq, windowControl, form, stepsRunContext); } private final class UserBulkChangeStepForm00 extends StepFormBasicController { - private FormLayoutContainer textContainer; private List<UserPropertyHandler> userPropertyHandlers; - private FormItem formitem; - private List<MultipleSelectionElement> checkBoxes; - private List<FormItem> formItems; + private final List<MultipleSelectionElement> checkBoxes = new ArrayList<>(); + @Autowired + private I18nManager i18nManager; + @Autowired + private UserManager userManager; @Autowired private UserBulkChangeManager ubcMan; public UserBulkChangeStepForm00(UserRequest ureq, WindowControl control, Form rootForm, StepsRunContext runContext) { super(ureq, control, rootForm, runContext, LAYOUT_VERTICAL, null); // use custom translator with fallback to user properties translator - UserManager um = UserManager.getInstance(); - setTranslator(um.getPropertyHandlerTranslator(getTranslator())); + setTranslator(userManager.getPropertyHandlerTranslator(getTranslator())); flc.setTranslator(getTranslator()); initForm(ureq); } @@ -147,12 +144,10 @@ class UserBulkChangeStep00 extends BasicStep { @Override protected void formOK(UserRequest ureq) { // process changed attributes - int i = 0; - HashMap<String, String> attributeChangeMap = new HashMap<String, String>(); - for (Iterator<MultipleSelectionElement> iterator = checkBoxes.iterator(); iterator.hasNext();) { - MultipleSelectionElement checkbox = iterator.next(); + HashMap<String, String> attributeChangeMap = new HashMap<>(); + for (MultipleSelectionElement checkbox:checkBoxes) { if (checkbox.isSelected(0)) { - FormItem formItem = formItems.get(i); + FormItem formItem = (FormItem)checkbox.getUserObject(); // first get the values from the hardcoded items if (formItem.getName().equals(UserBulkChangeManager.LANG_IDENTIFYER)) { SingleSelection selectField = (SingleSelection) formItem; @@ -182,7 +177,6 @@ class UserBulkChangeStep00 extends BasicStep { } } } - i++; } addToRunContext("attributeChangeMap", attributeChangeMap); addToRunContext("identitiesToEdit", identitiesToEdit); @@ -192,17 +186,13 @@ class UserBulkChangeStep00 extends BasicStep { @Override protected boolean validateFormLogic(UserRequest ureq) { boolean validChange = true; - UserManager um = UserManager.getInstance(); // loop through and check if any checkbox has been selected - int i = 0; - - for (Iterator<MultipleSelectionElement> iterator = checkBoxes.iterator(); iterator.hasNext();) { - MultipleSelectionElement checkbox = iterator.next(); + for (MultipleSelectionElement checkbox:checkBoxes) { if (checkbox.isSelected(0)) { Context vcContext = ubcMan.getDemoContext(getTranslator()); validChange = true; - FormItem formItem = formItems.get(i); + FormItem formItem = (FormItem)checkbox.getUserObject(); if (formItem instanceof TextElement) { TextElement propertyField = (TextElement) formItem; String inputFieldValue = propertyField.getValue(); @@ -217,7 +207,7 @@ class UserBulkChangeStep00 extends BasicStep { for (UserPropertyHandler handler : userPropertyHandlers) { if (handler.getName().equals(formItem.getName())) { // first check on mandatoryness - if (um.isMandatoryUserProperty(usageIdentifyer, handler) && ! StringHelper.containsNonWhitespace(evaluatedInputFieldValue)) { + if (userManager.isMandatoryUserProperty(usageIdentifyer, handler) && !StringHelper.containsNonWhitespace(evaluatedInputFieldValue)) { formItem.setErrorKey("form.name." + handler.getName() + ".error.empty", null); return false; } @@ -233,11 +223,9 @@ class UserBulkChangeStep00 extends BasicStep { } // special case: check password-syntax: - if (propertyField.getName().equals("password")) { - if (!um.syntaxCheckOlatPassword(evaluatedInputFieldValue)) { - propertyField.setErrorKey("error.password", new String[] { evaluatedInputFieldValue }); - return false; - } + if (propertyField.getName().equals("password")&& !userManager.syntaxCheckOlatPassword(evaluatedInputFieldValue)) { + propertyField.setErrorKey("error.password", new String[] { evaluatedInputFieldValue }); + return false; } // already done by form.visitAll -> validate(): @@ -249,27 +237,31 @@ class UserBulkChangeStep00 extends BasicStep { // propertyField.setValue(origInputFieldValue); } } - i++; } // for - addToRunContext("validChange", new Boolean(validChange)); + addToRunContext("validChange", Boolean.valueOf(validChange)); return true; } @Override - protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { - MultipleSelectionElement checkbox; - checkBoxes = new ArrayList<MultipleSelectionElement>(); - formItems = new ArrayList<FormItem>(); + protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) { + if(source instanceof MultipleSelectionElement && source.getUserObject() instanceof FormItem) { + MultipleSelectionElement checkbox = (MultipleSelectionElement)source; + FormItem item = (FormItem)checkbox.getUserObject(); + item.setVisible(checkbox.isAtLeastSelected(1)); + } + super.formInnerEvent(ureq, source, event); + } + @Override + protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { setFormTitle("title"); // text description of this Step - textContainer = FormLayoutContainer.createCustomFormLayout("index", getTranslator(), this.velocity_root + "/step0.html"); + FormLayoutContainer textContainer = FormLayoutContainer.createCustomFormLayout("index", getTranslator(), this.velocity_root + "/step0.html"); formLayout.add(textContainer); - textContainer.contextPut("userPropertyHandlers", UserManager.getInstance().getUserPropertyHandlersFor( + textContainer.contextPut("userPropertyHandlers", userManager.getUserPropertyHandlersFor( usageIdentifyerForAllProperties, isAdministrativeUser)); - Set<FormItem> targets; // Main layout is a vertical layout without left side padding. To format // the checkboxes properly we need a default layout for the remaining form // elements @@ -279,23 +271,19 @@ class UserBulkChangeStep00 extends BasicStep { // add input field for password Boolean canChangePwd = BaseSecurityModule.USERMANAGER_CAN_MODIFY_PWD; if (canChangePwd.booleanValue() || isOLATAdmin) { - checkbox = uifactory.addCheckboxesHorizontal("checkboxPWD", "form.name.pwd", innerFormLayout, new String[] { "changePWD" }, new String[] { "" }); - checkbox.select("changePWD", false); - checkbox.addActionListener(FormEvent.ONCLICK); - formitem = uifactory.addTextElement(UserBulkChangeManager.PWD_IDENTIFYER, "password", 127, null, innerFormLayout); - TextElement formEl = (TextElement) formitem; - formEl.setDisplaySize(35); - formitem.setLabel(null, null); - targets = new HashSet<FormItem>(); - targets.add(formitem); - RulesFactory.createHideRule(checkbox, null, targets, innerFormLayout); - RulesFactory.createShowRule(checkbox, "changePWD", targets, innerFormLayout); - checkBoxes.add(checkbox); - formItems.add(formitem); + MultipleSelectionElement passwordCheckEl = uifactory.addCheckboxesHorizontal("checkboxPWD", "form.name.pwd", innerFormLayout, new String[] { "changePWD" }, new String[] { "" }); + passwordCheckEl.select("changePWD", false); + passwordCheckEl.addActionListener(FormEvent.ONCLICK); + TextElement passwordTextEl = uifactory.addTextElement(UserBulkChangeManager.PWD_IDENTIFYER, "password", 127, null, innerFormLayout); + passwordTextEl.setDisplaySize(35); + passwordTextEl.setLabel(null, null); + passwordTextEl.setVisible(false); + checkBoxes.add(passwordCheckEl); + passwordCheckEl.setUserObject(passwordTextEl); } // add SingleSelect for language - Map<String, String> locdescs = I18nManager.getInstance().getEnabledLanguagesTranslated(); + Map<String, String> locdescs = i18nManager.getEnabledLanguagesTranslated(); Set<String> lkeys = locdescs.keySet(); String[] languageKeys = new String[lkeys.size()]; String[] languageValues = new String[lkeys.size()]; @@ -307,45 +295,37 @@ class UserBulkChangeStep00 extends BasicStep { languageValues[p] = locdescs.get(key); p++; } - checkbox = uifactory.addCheckboxesHorizontal("checkboxLang", "form.name.language", innerFormLayout, new String[] { "changeLang" }, new String[] { "" }); - checkbox.select("changeLang", false); - checkbox.addActionListener(FormEvent.ONCLICK); - formitem = uifactory.addDropdownSingleselect(UserBulkChangeManager.LANG_IDENTIFYER, innerFormLayout, languageKeys, languageValues, null); - formitem.setLabel(null, null); - targets = new HashSet<FormItem>(); - targets.add(formitem); - RulesFactory.createHideRule(checkbox, null, targets, innerFormLayout); - RulesFactory.createShowRule(checkbox, "changeLang", targets, innerFormLayout); - checkBoxes.add(checkbox); - formItems.add(formitem); + MultipleSelectionElement languageCheckEl = uifactory.addCheckboxesHorizontal("checkboxLang", "form.name.language", innerFormLayout, new String[] { "changeLang" }, new String[] { "" }); + languageCheckEl.select("changeLang", false); + languageCheckEl.addActionListener(FormEvent.ONCLICK); + SingleSelection languageSelectionEl = uifactory.addDropdownSingleselect(UserBulkChangeManager.LANG_IDENTIFYER, innerFormLayout, languageKeys, languageValues, null); + languageSelectionEl.setLabel(null, null); + languageSelectionEl.setVisible(false); + checkBoxes.add(languageCheckEl); + languageCheckEl.setUserObject(languageSelectionEl); // add checkboxes/formitems for userProperties defined in // src/serviceconfig/org/olat/_spring/olat_userconfig.xml -> Key: // org.olat.admin.user.bulkChange.UserBulkChangeStep00 - List<UserPropertyHandler> userPropHandlers = UserManager.getInstance().getUserPropertyHandlersFor(usageIdentifyer, isAdministrativeUser); - userPropertyHandlers = new ArrayList<UserPropertyHandler>(); + List<UserPropertyHandler> userPropHandlers = userManager.getUserPropertyHandlersFor(usageIdentifyer, isAdministrativeUser); + userPropertyHandlers = new ArrayList<>(); for (int i = 0; i < userPropHandlers.size(); i++) { UserPropertyHandler userPropertyHandler = userPropHandlers.get(i); //accept only no-unique properties if(!(userPropertyHandler instanceof GenericUnique127CharTextPropertyHandler)) { userPropertyHandlers.add(userPropertyHandler); - - checkbox = uifactory.addCheckboxesHorizontal("checkbox" + i, "form.name." + userPropertyHandler.getName(), innerFormLayout, + + MultipleSelectionElement checkboxEl = uifactory.addCheckboxesHorizontal("checkbox" + i, + "form.name." + userPropertyHandler.getName(), innerFormLayout, new String[] { "change" + userPropertyHandler.getName() }, new String[] { "" }); - checkbox.select("change" + userPropertyHandler.getName(), false); - checkbox.addActionListener(FormEvent.ONCLICK); - - formitem = userPropertyHandler.addFormItem(getLocale(), null, usageIdentifyer, isAdministrativeUser, innerFormLayout); - formitem.setLabel(null, null); - - targets = new HashSet<FormItem>(); - targets.add(formitem); + checkboxEl.select("change" + userPropertyHandler.getName(), false); + checkboxEl.addActionListener(FormEvent.ONCLICK); - RulesFactory.createHideRule(checkbox, null, targets, innerFormLayout); - RulesFactory.createShowRule(checkbox, "change" + userPropertyHandler.getName(), targets, innerFormLayout); - - checkBoxes.add(checkbox); - formItems.add(formitem); + FormItem formItem = userPropertyHandler.addFormItem(getLocale(), null, usageIdentifyer, isAdministrativeUser, innerFormLayout); + formItem.setLabel(null, null); + formItem.setVisible(false); + checkboxEl.setUserObject(formItem); + checkBoxes.add(checkboxEl); } } } diff --git a/src/main/java/org/olat/core/gui/components/form/flexible/DependencyRuleApplayable.java b/src/main/java/org/olat/core/gui/components/form/flexible/DependencyRuleApplayable.java deleted file mode 100644 index e8a5d04184e..00000000000 --- a/src/main/java/org/olat/core/gui/components/form/flexible/DependencyRuleApplayable.java +++ /dev/null @@ -1,50 +0,0 @@ -/** -* OLAT - Online Learning and Training<br> -* http://www.olat.org -* <p> -* Licensed under the Apache License, Version 2.0 (the "License"); <br> -* you may not use this file except in compliance with the License.<br> -* You may obtain a copy of the License at -* <p> -* http://www.apache.org/licenses/LICENSE-2.0 -* <p> -* Unless required by applicable law or agreed to in writing,<br> -* software distributed under the License is distributed on an "AS IS" BASIS, <br> -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> -* See the License for the specific language governing permissions and <br> -* limitations under the License. -* <p> -* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> -* University of Zurich, Switzerland. -* <hr> -* <a href="http://www.openolat.org"> -* OpenOLAT - Online Learning and Training</a><br> -* This file has been modified by the OpenOLAT community. Changes are licensed -* under the Apache 2.0 license as the original file. -* <p> -*/ -package org.olat.core.gui.components.form.flexible; - -import java.util.Set; - - -/** - * Description:<br> - * TODO: patrickb Class Description for DependencyRuleApplayable - * - * <P> - * Initial Date: 13.07.2007 <br> - * @author patrickb - */ -public interface DependencyRuleApplayable { - - /** - * custom rule interface - * @param triggerElement - * @param triggerVal - * @param targets - * @param actiontype - */ - void apply(FormItem triggerElement, Object triggerVal, Set<FormItem> targets); - -} diff --git a/src/main/java/org/olat/core/gui/components/form/flexible/FormItemContainer.java b/src/main/java/org/olat/core/gui/components/form/flexible/FormItemContainer.java index 7ef17d1255c..c1ec4beb01b 100644 --- a/src/main/java/org/olat/core/gui/components/form/flexible/FormItemContainer.java +++ b/src/main/java/org/olat/core/gui/components/form/flexible/FormItemContainer.java @@ -28,13 +28,8 @@ package org.olat.core.gui.components.form.flexible; import java.util.Collection; import java.util.Map; -import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.form.flexible.impl.Form; - - - - /** * Description:<br> * FormContainer and FormComponent -> Composite Pattern @@ -105,21 +100,6 @@ public interface FormItemContainer extends FormItem, FormItemCollection { * @param rootForm */ public void setRootForm(Form rootForm); - - /** - * add a dependency rule between a form item source and typically one or more - * form item targets. See {@link FormItemDependencyRule} for more information. - * @see FormItemDependencyRule - * @param depRule - */ - public void addDependencyRule(FormItemDependencyRule depRule); - - /** - * - * @param ureq - * @param dispatchFormItem - */ - public void evalDependencyRuleSetFor(UserRequest ureq, FormItem formItem); /** * @param string diff --git a/src/main/java/org/olat/core/gui/components/form/flexible/FormItemDependencyRule.java b/src/main/java/org/olat/core/gui/components/form/flexible/FormItemDependencyRule.java deleted file mode 100644 index 672188783d7..00000000000 --- a/src/main/java/org/olat/core/gui/components/form/flexible/FormItemDependencyRule.java +++ /dev/null @@ -1,77 +0,0 @@ -/** -* OLAT - Online Learning and Training<br> -* http://www.olat.org -* <p> -* Licensed under the Apache License, Version 2.0 (the "License"); <br> -* you may not use this file except in compliance with the License.<br> -* You may obtain a copy of the License at -* <p> -* http://www.apache.org/licenses/LICENSE-2.0 -* <p> -* Unless required by applicable law or agreed to in writing,<br> -* software distributed under the License is distributed on an "AS IS" BASIS, <br> -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> -* See the License for the specific language governing permissions and <br> -* limitations under the License. -* <p> -* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> -* University of Zurich, Switzerland. -* <hr> -* <a href="http://www.openolat.org"> -* OpenOLAT - Online Learning and Training</a><br> -* This file has been modified by the OpenOLAT community. Changes are licensed -* under the Apache 2.0 license as the original file. -* <p> -*/ -package org.olat.core.gui.components.form.flexible; - -import java.util.Set; - - -/** - * Description:<br> - * TODO: patrickb Class Description for FormItemDependencyRule - * - * <P> - * Initial Date: 09.02.2007 <br> - * @author patrickb - */ -public interface FormItemDependencyRule { - /** - * which form element triggers this rule - * @return - */ - public FormItem getTriggerElement(); - - /** - * which trigger value in the form element - * @return - */ - public Object getTriggerValue(); - - /** - * - * @return - */ - public Set<FormItem> getTargetElements(); - - /** - * Checks if rule is triggered and executes the desired actions on the target - * elements. - * returns true if rule was applied - */ - public boolean applyRule(FormItemContainer layoutContainer); - - /** - * identify this rule without taking the target elements into account. - * - * @return - */ - public String getIdentifier(); - - /** - * - * @param applayable - */ - public void setDependencyRuleApplayable(DependencyRuleApplayable applayable); -} diff --git a/src/main/java/org/olat/core/gui/components/form/flexible/impl/Form.java b/src/main/java/org/olat/core/gui/components/form/flexible/impl/Form.java index eaf024f4926..3d0accbf4ed 100644 --- a/src/main/java/org/olat/core/gui/components/form/flexible/impl/Form.java +++ b/src/main/java/org/olat/core/gui/components/form/flexible/impl/Form.java @@ -144,14 +144,14 @@ public class Form { private static final OLog log = Tracing.createLoggerFor(Form.class); // - public final static String FORMCMD = "fid"; - public final static String FORMID = "ofo_"; - public final static String FORM_UNDEFINED="undefined"; + public static final String FORMCMD = "fid"; + public static final String FORMID = "ofo_"; + public static final String FORM_UNDEFINED="undefined"; - public final static int REQUEST_ERROR_NO_ERROR = -1; - public final static int REQUEST_ERROR_GENERAL = 1; - public final static int REQUEST_ERROR_FILE_EMPTY = 2; - public final static int REQUEST_ERROR_UPLOAD_LIMIT_EXCEEDED = 3; + public static final int REQUEST_ERROR_NO_ERROR = -1; + public static final int REQUEST_ERROR_GENERAL = 1; + public static final int REQUEST_ERROR_FILE_EMPTY = 2; + public static final int REQUEST_ERROR_UPLOAD_LIMIT_EXCEEDED = 3; private String formName; private String dispatchFieldId; @@ -168,10 +168,10 @@ public class Form { private boolean isHideDirtyMarkingMessage = false; private boolean multipartEnabled = false; // temporary form data, only valid within execution of evalFormRequest() - private Map<String,String[]> requestParams = new HashMap<String,String[]>(); - private Map<String, File> requestMultipartFiles = new HashMap<String,File>(); - private Map<String, String> requestMultipartFileNames = new HashMap<String,String>(); - private Map<String, String> requestMultipartFileMimeTypes = new HashMap<String,String>(); + private Map<String,String[]> requestParams = new HashMap<>(); + private Map<String, File> requestMultipartFiles = new HashMap<>(); + private Map<String, String> requestMultipartFileNames = new HashMap<>(); + private Map<String, String> requestMultipartFileMimeTypes = new HashMap<>(); private int requestError = REQUEST_ERROR_NO_ERROR; private Form() { @@ -194,7 +194,7 @@ public class Form { // this is where the formitems go to form.formLayout = formLayout; form.formLayout.setRootForm(form); - form.formListeners = new ArrayList<FormBasicController>(1); + form.formListeners = new ArrayList<>(1); if(listener instanceof FormBasicController){ form.formListeners.add((FormBasicController)listener); } @@ -204,7 +204,6 @@ public class Form { // renders header + <formLayout> + footer of html form form.formWrapperComponent = new FormWrapperContainer(id, name, translator, form); form.formWrapperComponent.addListener(listener); - //form.formWrapperComponent.put(formLayout.getComponent().getComponentName(), formLayout.getComponent()); // generate name for form and dispatch uri hidden field form.formName = Form.FORMID + form.formWrapperComponent.getDispatchID(); @@ -243,9 +242,7 @@ public class Form { //assume a click on this item dispatchUri = FormBaseComponentIdProvider.DISPPREFIX + submitFormItem.getComponent().getDispatchID(); action = FormEvent.ONCLICK; - }else{ - // instead of - // throw new AssertException("You have an input field but no submit item defined! this is no good if enter is pressed."); + } else { // assume a desired implicit form submit // see also OLAT-3141 implicitFormSubmit = true; @@ -279,37 +276,24 @@ public class Form { //.......... the code goes further with step 3......................... if (implicitFormSubmit) { //implicit Submit (Press Enter without on a Field without submit item.) - // see also OLAT-3141 submit(ureq); }else{ if (dispatchFormItem == null) { // source not found. This "never happens". Try to produce some hints. - String fbc = new String(); + StringBuilder fbc = new StringBuilder(128); for (FormBasicController i: formListeners) { if (fbc.length()>0) { - fbc += ","; + fbc.append(","); } - fbc+=(i.getClass().getName()); + fbc.append(i.getClass().getName()); } log.warn("OLAT-5061: Could not determine request source in FlexiForm >"+formName+"<. Check >"+fbc+"<", null); - - // TODO: what now? // Assuming the same as "implicitFormSubmit" for now. submit(ureq); } else { - // **************************************** - // explicit Submit or valid form dispatch * - // **************************************** + // explicit Submit or valid form dispatch dispatchFormItem.doDispatchFormRequest(ureq); - // step 3: find parent container of dispatched component - // .......... check dependency rules - // .......... apply dependency rules - FindParentFormComponentVisitor fpfcv = new FindParentFormComponentVisitor( - dispatchFormItem); - ct = new FormComponentTraverser(fpfcv, formLayout, false); - ct.visitAll(ureq); - fpfcv.getParent().evalDependencyRuleSetFor(ureq, dispatchFormItem); } } // @@ -331,9 +315,9 @@ public class Form { part.write(tmpFile.getAbsolutePath()); // Cleanup IE filenames that are absolute - int slashpos = fileName.lastIndexOf("/"); + int slashpos = fileName.lastIndexOf('/'); if (slashpos != -1) fileName = fileName.substring(slashpos + 1); - slashpos = fileName.lastIndexOf("\\"); + slashpos = fileName.lastIndexOf('\\'); if (slashpos != -1) fileName = fileName.substring(slashpos + 1); requestMultipartFiles.put(name, tmpFile); @@ -372,10 +356,7 @@ public class Form { if (contentType == null) { return false; } - if (contentType.toLowerCase(Locale.ENGLISH).startsWith("multipart/")) { - return true; - } - return false; + return contentType.toLowerCase(Locale.ENGLISH).startsWith("multipart/"); } /** @@ -406,14 +387,10 @@ public class Form { if (values == null) { // First element for this key values = new String[]{value}; - //use log.debug instead of System.out.println("PARAMS:"+key+" :: "+value); - } - else { + } else { // A multi-key element (e.g. radio button) values = ArrayHelper.addToArray(values, value, true); - //use log.debug instead of System.out.println("PARAMS:"+key+" ::[array of values]"); } - requestParams.put(key, values); } @@ -489,9 +466,7 @@ public class Form { ResettingFormComponentVisitor rfcv = new ResettingFormComponentVisitor(); FormComponentTraverser ct = new FormComponentTraverser(rfcv, formLayout, false); ct.visitAll(ureq);//calls reset on all elements! - // - evalAllFormDependencyRules(ureq); - // + formWrapperComponent.fireFormEvent(ureq, FormEvent.RESET); hasAlreadyFired = true; } @@ -609,11 +584,7 @@ public class Form { return requestMultipartFiles.keySet(); } - /** - * Description:<br> - * TODO: patrickb Class Description for EvaluatingFormComponentVisitor - * <P> * Initial Date: 04.12.2006 <br> * * @author patrickb @@ -670,55 +641,9 @@ public class Form { return true; } } - - private class FindParentFormComponentVisitor implements FormComponentVisitor { - - private FormItem child; - private FormItemContainer parentContainer = formLayout; - - public FindParentFormComponentVisitor(FormItem child){ - this.child = child; - } - - public FormItemContainer getParent(){ - return parentContainer; - } - - public boolean visit(FormItem comp, UserRequest ureq) { - if (comp instanceof FormItemContainer) { - FormItemContainer new_name = (FormItemContainer) comp; - if(new_name.hasFormComponent(child)){ - parentContainer = (FormItemContainer)comp; - return false; - } - } - return true; - } - - } - - - private static class FormDependencyRulesInitComponentVisitor implements FormComponentVisitor { - - public boolean visit(FormItem comp, UserRequest ureq) { - if (comp instanceof FormItemContainer) { - FormItemContainer fic = (FormItemContainer)comp; - Iterable<FormItem> pairs = fic.getFormItems(); - //go to next container if no elements inside - if(pairs != null) { - //otherwise iterate overall elements and evaluate dependency rules - for (FormItem item : pairs) { - fic.evalDependencyRuleSetFor(ureq, item); - } - } - } - return true; - } - - } private static class ValidatingFormComponentVisitor implements FormComponentVisitor { - final List<ValidationStatus> tmp = new ArrayList<ValidationStatus>(); + final List<ValidationStatus> tmp = new ArrayList<>(); public ValidationStatus[] getStatus() { return sort(tmp); @@ -803,18 +728,10 @@ public class Form { return action; } - /** - * @param ureq - */ - void evalAllFormDependencyRules(UserRequest ureq) { - FormDependencyRulesInitComponentVisitor fdrocv = new FormDependencyRulesInitComponentVisitor(); - FormComponentTraverser ct = new FormComponentTraverser(fdrocv, formLayout, false); - ct.visitAll(ureq);//visit all container and eval container with its elements! - } - public boolean isSubmittedAndValid(){ return isValidAndSubmitted; } + public void forceSubmittedAndValid() { isValidAndSubmitted = true; } diff --git a/src/main/java/org/olat/core/gui/components/form/flexible/impl/FormLayoutContainer.java b/src/main/java/org/olat/core/gui/components/form/flexible/impl/FormLayoutContainer.java index 12059d8f213..63d2fc38aac 100644 --- a/src/main/java/org/olat/core/gui/components/form/flexible/impl/FormLayoutContainer.java +++ b/src/main/java/org/olat/core/gui/components/form/flexible/impl/FormLayoutContainer.java @@ -29,7 +29,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; @@ -37,7 +36,6 @@ import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.Component; import org.olat.core.gui.components.form.flexible.FormItem; import org.olat.core.gui.components.form.flexible.FormItemContainer; -import org.olat.core.gui.components.form.flexible.FormItemDependencyRule; import org.olat.core.gui.components.form.flexible.FormMultipartItem; import org.olat.core.gui.components.velocity.VelocityContainer; import org.olat.core.gui.control.Disposable; @@ -85,7 +83,6 @@ public class FormLayoutContainer extends FormItemImpl implements FormItemContain private List<String> formComponentsNames; private Map<String,FormItem> listeningOnlyFormComponents; private boolean hasRootForm=false; - private Map<String, Map<String, FormItemDependencyRule>> dependencyRules; /** @@ -125,11 +122,10 @@ public class FormLayoutContainer extends FormItemImpl implements FormItemContain formLayoutContainer.contextPut("f", new FormDecorator(this)); // this container manages the form items, the GUI form item componentes are // managed in the associated velocitycontainer - formComponentsNames = new ArrayList<String>(5); + formComponentsNames = new ArrayList<>(5); formLayoutContainer.contextPut("formitemnames", formComponentsNames); - formComponents = new HashMap<String, FormItem>(); - listeningOnlyFormComponents = new HashMap<String, FormItem>(); - dependencyRules = new HashMap<String, Map<String, FormItemDependencyRule>>(); + formComponents = new HashMap<>(); + listeningOnlyFormComponents = new HashMap<>(); } @@ -340,14 +336,14 @@ public class FormLayoutContainer extends FormItemImpl implements FormItemContain @Override public Iterable<FormItem> getFormItems() { - List<FormItem> merged = new ArrayList<FormItem>(formComponents.values()); + List<FormItem> merged = new ArrayList<>(formComponents.values()); merged.addAll(listeningOnlyFormComponents.values()); return merged; } @Override public Map<String, FormItem> getFormComponents() { - Map<String,FormItem> merged = new HashMap<String, FormItem>(formComponents); + Map<String,FormItem> merged = new HashMap<>(formComponents); merged.putAll(listeningOnlyFormComponents); return Collections.unmodifiableMap(merged); } @@ -455,43 +451,6 @@ public class FormLayoutContainer extends FormItemImpl implements FormItemContain public void setDirty(boolean dirty){ formLayoutContainer.setDirty(dirty); } - - /** - * @see org.olat.core.gui.components.form.flexible.api.FormItemContainer#addDependencyRule(org.olat.core.gui.components.form.flexible.api.FormItemDependencyRule) - */ - public void addDependencyRule(FormItemDependencyRule depRule) { - String key = depRule.getTriggerElement().getName(); - Map<String, FormItemDependencyRule> rules; - if(dependencyRules.containsKey(key)){ - //already rules for this element - rules = dependencyRules.get(key); - }else{ - //no rules yet, create - rules = new HashMap<String, FormItemDependencyRule>(); - dependencyRules.put(key, rules); - } - rules.put(depRule.getIdentifier(), depRule); - } - - - /** - * @see org.olat.core.gui.components.form.flexible.api.FormItemContainer#evalDependencyRuleSetFor(org.olat.core.gui.UserRequest, org.olat.core.gui.components.form.flexible.api.FormItem) - */ - @Override - public void evalDependencyRuleSetFor(UserRequest ureq, FormItem dispatchFormItem) { - String key = dispatchFormItem.getName(); - if(dependencyRules.containsKey(key)){ - Map<String, FormItemDependencyRule> ruleSet = dependencyRules.get(key); - Collection<FormItemDependencyRule> rules = ruleSet.values(); - for (Iterator<FormItemDependencyRule> iter = rules.iterator(); iter.hasNext();) { - FormItemDependencyRule tmp = iter.next(); - if (tmp.applyRule(this)) { - setDirty(true); - } - } - } - - } /** * @see org.olat.core.gui.components.form.flexible.FormItemImpl#setEnabled(boolean) diff --git a/src/main/java/org/olat/core/gui/components/form/flexible/impl/FormWrapperContainer.java b/src/main/java/org/olat/core/gui/components/form/flexible/impl/FormWrapperContainer.java index 07e4ebb555b..32d7b476922 100644 --- a/src/main/java/org/olat/core/gui/components/form/flexible/impl/FormWrapperContainer.java +++ b/src/main/java/org/olat/core/gui/components/form/flexible/impl/FormWrapperContainer.java @@ -33,16 +33,14 @@ import org.olat.core.gui.components.Component; import org.olat.core.gui.components.ComponentCollection; import org.olat.core.gui.components.ComponentRenderer; import org.olat.core.gui.control.Event; -import org.olat.core.gui.render.ValidationResult; import org.olat.core.gui.translator.Translator; class FormWrapperContainer extends AbstractComponent implements ComponentCollection { // Renderer - private static ComponentRenderer RENDERER = new FormWrapperContainerRenderer(); + private static final ComponentRenderer RENDERER = new FormWrapperContainerRenderer(); // associated form knows the choosen layout private Form form; - private boolean firstInit; /** * @param id A fix identifier for the container @@ -53,7 +51,6 @@ class FormWrapperContainer extends AbstractComponent implements ComponentCollect public FormWrapperContainer(String id, String name, Translator translator, Form form) { super(id, name, translator); this.form = form; - firstInit = false; } public String getDispatchFieldId() { @@ -124,20 +121,6 @@ class FormWrapperContainer extends AbstractComponent implements ComponentCollect fireEvent(ureq, org.olat.core.gui.components.form.Form.EVNT_VALIDATION_NOK); } } - - /** - * @see org.olat.core.gui.components.Component#validate(org.olat.core.gui.UserRequest, org.olat.core.gui.render.ValidationResult) - */ - @Override - public void validate(UserRequest ureq, ValidationResult vr) { - super.validate(ureq, vr); - if(!firstInit){ - //initialise dependency rules - form.evalAllFormDependencyRules(ureq); - // - firstInit = true; - } - } @Override public ComponentRenderer getHTMLRendererSingleton() { diff --git a/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/FormItemDependencyRuleImpl.java b/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/FormItemDependencyRuleImpl.java deleted file mode 100644 index eca2dedef80..00000000000 --- a/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/FormItemDependencyRuleImpl.java +++ /dev/null @@ -1,159 +0,0 @@ -/** -* OLAT - Online Learning and Training<br> -* http://www.olat.org -* <p> -* Licensed under the Apache License, Version 2.0 (the "License"); <br> -* you may not use this file except in compliance with the License.<br> -* You may obtain a copy of the License at -* <p> -* http://www.apache.org/licenses/LICENSE-2.0 -* <p> -* Unless required by applicable law or agreed to in writing,<br> -* software distributed under the License is distributed on an "AS IS" BASIS, <br> -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> -* See the License for the specific language governing permissions and <br> -* limitations under the License. -* <p> -* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> -* University of Zurich, Switzerland. -* <hr> -* <a href="http://www.openolat.org"> -* OpenOLAT - Online Learning and Training</a><br> -* This file has been modified by the OpenOLAT community. Changes are licensed -* under the Apache 2.0 license as the original file. -* <p> -*/ -package org.olat.core.gui.components.form.flexible.impl.rules; - -import java.util.Iterator; -import java.util.Set; - -import org.olat.core.gui.components.form.flexible.DependencyRuleApplayable; -import org.olat.core.gui.components.form.flexible.FormItem; -import org.olat.core.gui.components.form.flexible.FormItemContainer; -import org.olat.core.gui.components.form.flexible.FormItemDependencyRule; -import org.olat.core.logging.AssertException; - -/** - * Description:<br> - * TODO: patrickb Class Description for FormItemDependencyRuleImpl - * <P> - * Initial Date: 09.02.2007 <br> - * - * @author patrickb - */ -public abstract class FormItemDependencyRuleImpl implements FormItemDependencyRule { - public static final int MAKE_INVISIBLE = 0; - public static final int MAKE_VISIBLE = 1; - public static final int MAKE_READONLY = 2; - public static final int MAKE_WRITABLE = 3; - public static final int HIDE_ERROR = 4; - public static final int RESET = 5; - public static final int CUSTOM = 16; - - protected Object triggerVal; - protected FormItem triggerElement; - protected Set<FormItem> targets; - private int actiontype; - private String identifier; - - private DependencyRuleApplayable applayable = null; - - - /** - * @param triggerElement - * @param triggerValue - * @param targets - */ - public FormItemDependencyRuleImpl(FormItem triggerElement, Object triggerValue, Set<FormItem> targets, int type) { - this.triggerVal = triggerValue; - this.triggerElement = triggerElement; - this.targets = targets; - this.actiontype = type; - // - this.identifier = triggerElement.getName(); - this.identifier += "~" + triggerValue; - this.identifier += "~" + type; - this.identifier += "~" + targets.hashCode(); - - } - - /** - * @see org.olat.core.gui.components.form.flexible.api.FormItemDependencyRule#applyRule() - */ - public boolean applyRule(FormItemContainer formLayout) { - if (!doesTrigger() || targets == null) { - // stop applying - return false; - } - /* - * apply rule - */ - if (actiontype == FormItemDependencyRuleImpl.CUSTOM) { - applayable.apply(triggerElement, triggerVal, targets); - } else { - for (Iterator<FormItem> iter = targets.iterator(); iter.hasNext();) { - FormItem element = iter.next(); - switch (actiontype) { - case FormItemDependencyRuleImpl.MAKE_INVISIBLE: - element.setVisible(false); - break; - case FormItemDependencyRuleImpl.MAKE_VISIBLE: - element.setVisible(true); - break; - case FormItemDependencyRuleImpl.MAKE_READONLY: - element.setEnabled(false); - break; - case FormItemDependencyRuleImpl.MAKE_WRITABLE: - element.setEnabled(true); - break; - case FormItemDependencyRuleImpl.HIDE_ERROR: - element.showError(false); - break; - case FormItemDependencyRuleImpl.RESET: - element.reset(); - break; - default: - throw new AssertException("unsupported action in dependency rule"); - } - } - } - - return true; - } - - public void setDependencyRuleApplayable(DependencyRuleApplayable applayable){ - this.applayable = applayable; - } - - abstract protected boolean doesTrigger(); - - /** - * @see org.olat.core.gui.components.form.flexible.api.FormItemDependencyRule#getIdentifier() - */ - public String getIdentifier() { - return identifier; - } - - /** - * @see org.olat.core.gui.components.form.flexible.api.FormItemDependencyRule#getTargetElements() - */ - public Set<FormItem> getTargetElements() { - return targets; - } - - /** - * @see org.olat.core.gui.components.form.flexible.api.FormItemDependencyRule#getTriggerElement() - */ - public FormItem getTriggerElement() { - return triggerElement; - } - - /** - * @see org.olat.core.gui.components.form.flexible.api.FormItemDependencyRule#getTriggerValue() - */ - public Object getTriggerValue() { - return triggerVal; - } - -} diff --git a/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/MultiSelectionTriggerdDependencyRule.java b/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/MultiSelectionTriggerdDependencyRule.java deleted file mode 100644 index 3ccbdf36f2a..00000000000 --- a/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/MultiSelectionTriggerdDependencyRule.java +++ /dev/null @@ -1,67 +0,0 @@ -/** -* OLAT - Online Learning and Training<br> -* http://www.olat.org -* <p> -* Licensed under the Apache License, Version 2.0 (the "License"); <br> -* you may not use this file except in compliance with the License.<br> -* You may obtain a copy of the License at -* <p> -* http://www.apache.org/licenses/LICENSE-2.0 -* <p> -* Unless required by applicable law or agreed to in writing,<br> -* software distributed under the License is distributed on an "AS IS" BASIS, <br> -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> -* See the License for the specific language governing permissions and <br> -* limitations under the License. -* <p> -* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> -* University of Zurich, Switzerland. -* <hr> -* <a href="http://www.openolat.org"> -* OpenOLAT - Online Learning and Training</a><br> -* This file has been modified by the OpenOLAT community. Changes are licensed -* under the Apache 2.0 license as the original file. -* <p> -*/ -package org.olat.core.gui.components.form.flexible.impl.rules; - -import java.util.Collection; -import java.util.Set; - -import org.olat.core.gui.components.form.flexible.FormItem; -import org.olat.core.gui.components.form.flexible.FormItemDependencyRule; -import org.olat.core.gui.components.form.flexible.elements.MultipleSelectionElement; - -/** - * Description:<br> - * TODO: patrickb Class Description for MultiSelectionTriggerdDependencyRule - * - * <P> - * Initial Date: 11.02.2007 <br> - * @author patrickb - */ -class MultiSelectionTriggerdDependencyRule extends FormItemDependencyRuleImpl implements FormItemDependencyRule { - - public MultiSelectionTriggerdDependencyRule(MultipleSelectionElement triggerElement, String triggerValue, Set<FormItem> targets, int type) { - super(triggerElement, triggerValue, targets, type); - } - - /** - * @see org.olat.core.gui.components.form.flexible.rules.FormItemDependencyRuleImpl#doesTrigger() - */ - @Override - protected boolean doesTrigger() { - MultipleSelectionElement mse = (MultipleSelectionElement)triggerElement; - Collection<String> selectedKeys = mse.getSelectedKeys(); - - boolean retval = false; - if(triggerVal == null){ - //meaning no selection in a multi selection element - retval = selectedKeys.isEmpty(); - } else { - //check that value is in selection - retval = selectedKeys.contains(triggerVal); - } - return retval; - } -} diff --git a/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/RulesFactory.java b/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/RulesFactory.java deleted file mode 100644 index c550157d63a..00000000000 --- a/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/RulesFactory.java +++ /dev/null @@ -1,273 +0,0 @@ -/** -* OLAT - Online Learning and Training<br> -* http://www.olat.org -* <p> -* Licensed under the Apache License, Version 2.0 (the "License"); <br> -* you may not use this file except in compliance with the License.<br> -* You may obtain a copy of the License at -* <p> -* http://www.apache.org/licenses/LICENSE-2.0 -* <p> -* Unless required by applicable law or agreed to in writing,<br> -* software distributed under the License is distributed on an "AS IS" BASIS, <br> -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> -* See the License for the specific language governing permissions and <br> -* limitations under the License. -* <p> -* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> -* University of Zurich, Switzerland. -* <hr> -* <a href="http://www.openolat.org"> -* OpenOLAT - Online Learning and Training</a><br> -* This file has been modified by the OpenOLAT community. Changes are licensed -* under the Apache 2.0 license as the original file. -* <p> -*/ -package org.olat.core.gui.components.form.flexible.impl.rules; - -import java.util.HashSet; -import java.util.Set; - -import org.olat.core.gui.components.form.flexible.FormItem; -import org.olat.core.gui.components.form.flexible.FormItemContainer; -import org.olat.core.gui.components.form.flexible.FormItemDependencyRule; -import org.olat.core.gui.components.form.flexible.elements.MultipleSelectionElement; -import org.olat.core.gui.components.form.flexible.elements.SingleSelection; -import org.olat.core.gui.components.form.flexible.elements.TextElement; -import org.olat.core.logging.AssertException; - -/** - * Description:<br> - * TODO: patrickb Class Description for RulesFactory - * - * <P> - * Initial Date: 10.02.2007 <br> - * - * @author patrickb - */ -public class RulesFactory { - /** - * Creates a custom rule which is triggered whenever - * <code>triggerElement</code> is set to <code>triggerValue</code>. The code - * which gets executed resides in the <code>apply</code> method of a - * {@link DependencyRuleApplayable} object. An implementation that executes if - * a trigger element changes to "true" could look like this: - * - * <pre> - * {@code - * RulesFactory.createCustomRule(triggerElement, "true", new HashSet<FormItem>(Arrays.asList(target1, target2)), formLayout).setDependencyRuleApplayable(new DependencyRuleApplayable() { - * public void apply(FormItem triggerElement, Object triggerVal, Set<FormItem> targets) { - * for (FormItem target : targets) { - * target.setEnabled(true); - * } - * } - * }); - * } - * </pre> - * - * (Note that this example uses an anonymous class which makes it unnecessary - * for you to create a separate class which implements - * <code>DependencyRuleApplayable</code> for each of your rules.) Don't forget - * to add action listeners for - * {@link org.olat.core.gui.components.form.flexible.impl.FormEvent.ONCHANGE} - * to your trigger elements. - * - * @param triggerElement The element that is being watched for changes. - * @param triggerValue Triggers if the <code>triggerElement</code>'s key - * changes to <code>triggerValue</code> - * @param targets The targets. - * @param formLayout The container. - * @return The rule - * @see DependencyRuleApplayable - */ - public static FormItemDependencyRule createCustomRule(FormItem triggerElement, Object triggerValue, Set<FormItem> targets, - FormItemContainer formLayout) { - FormItemDependencyRule fidr = createRule(triggerElement, triggerValue, targets, FormItemDependencyRuleImpl.CUSTOM); - formLayout.addDependencyRule(fidr); - return fidr; - } - - /** - * creates a custom rule, it is a must to define and set the applayable - * - * @param triggerElement - * @param triggerValue - * @param target - * @param formLayout - * @return - */ - public static FormItemDependencyRule createCustomRule(FormItem triggerElement, Object triggerValue, FormItem target, - FormItemContainer formLayout) { - Set<FormItem> targets = new HashSet<FormItem>(); - targets.add(target); - return createCustomRule(triggerElement, triggerValue, targets, formLayout); - } - - /** - * creates a reset rule - * - * @param triggerElement - * @param triggerValue - * @param targets - * @param formLayout - * @return - */ - public static FormItemDependencyRule createResetRule(FormItem triggerElement, Object triggerValue, Set<FormItem> targets, - FormItemContainer formLayout) { - FormItemDependencyRule fidr = createRule(triggerElement, triggerValue, targets, FormItemDependencyRuleImpl.RESET); - formLayout.addDependencyRule(fidr); - return fidr; - } - - /** - * creates a reset rule - * - * @param triggerElement - * @param triggerValue - * @param target - * @param formLayout - * @return - */ - public static FormItemDependencyRule createResetRule(FormItem triggerElement, Object triggerValue, FormItem target, - FormItemContainer formLayout) { - Set<FormItem> targets = new HashSet<FormItem>(); - targets.add(target); - return createResetRule(triggerElement, triggerValue, targets, formLayout); - } - - /** - * - * @param triggerElement - * @param triggerValue - * @param targets - * @return - */ - public static FormItemDependencyRule createHideRule(FormItem triggerElement, Object triggerValue, Set<FormItem> targets, - FormItemContainer formLayout) { - FormItemDependencyRule fidr = createRule(triggerElement, triggerValue, targets, FormItemDependencyRuleImpl.MAKE_INVISIBLE); - formLayout.addDependencyRule(fidr); - return fidr; - } - - /** - * - * @param triggerElement - * @param triggerValue - * @param target - * @return - */ - public static FormItemDependencyRule createHideRule(FormItem triggerElement, Object triggerValue, FormItem target, - FormItemContainer formLayout) { - Set<FormItem> targets = new HashSet<FormItem>(); - targets.add(target); - return createHideRule(triggerElement, triggerValue, targets, formLayout); - } - - /** - * - * @param triggerElement - * @param triggerValue - * @param targets - * @return - */ - public static FormItemDependencyRule createShowRule(FormItem triggerElement, Object triggerValue, Set<FormItem> targets, - FormItemContainer formLayout) { - FormItemDependencyRule fidr = createRule(triggerElement, triggerValue, targets, FormItemDependencyRuleImpl.MAKE_VISIBLE); - formLayout.addDependencyRule(fidr); - return fidr; - } - - /** - * - * @param triggerElement - * @param triggerValue - * @param target - * @return - */ - public static FormItemDependencyRule createShowRule(FormItem triggerElement, Object triggerValue, FormItem target, - FormItemContainer formLayout) { - Set<FormItem> targets = new HashSet<FormItem>(); - targets.add(target); - return createShowRule(triggerElement, triggerValue, targets, formLayout); - } - - /** - * - * @param triggerElement - * @param triggerValue - * @param targets - * @return - */ - public static FormItemDependencyRule createReadOnlyRule(FormItem triggerElement, Object triggerValue, Set<FormItem> targets, - FormItemContainer formLayout) { - FormItemDependencyRule fidr = createRule(triggerElement, triggerValue, targets, FormItemDependencyRuleImpl.MAKE_READONLY); - formLayout.addDependencyRule(fidr); - return fidr; - } - - /** - * - * @param triggerElement - * @param triggerValue - * @param target - * @return - */ - public static FormItemDependencyRule createReadOnlyRule(FormItem triggerElement, Object triggerValue, FormItem target, - FormItemContainer formLayout) { - Set<FormItem> targets = new HashSet<FormItem>(); - targets.add(target); - return createReadOnlyRule(triggerElement, triggerValue, targets, formLayout); - } - - /** - * - * @param triggerElement - * @param triggerValue - * @param targets - * @return - */ - public static FormItemDependencyRule createWritableRule(FormItem triggerElement, Object triggerValue, Set<FormItem> targets, - FormItemContainer formLayout) { - FormItemDependencyRule fidr = createRule(triggerElement, triggerValue, targets, FormItemDependencyRuleImpl.MAKE_WRITABLE); - formLayout.addDependencyRule(fidr); - return fidr; - } - - /** - * - * @param triggerElement - * @param triggerValue - * @param target - * @return - */ - public static FormItemDependencyRule createWritableRule(FormItem triggerElement, Object triggerValue, FormItem target, - FormItemContainer formLayout) { - Set<FormItem> targets = new HashSet<FormItem>(); - targets.add(target); - return createWritableRule(triggerElement, triggerValue, targets, formLayout); - } - - /** - * - * @param triggerElement - * @param triggerValue - * @param targets - * @param type - * @return - */ - private static FormItemDependencyRule createRule(FormItem triggerElement, Object triggerValue, Set<FormItem> targets, int type) { - FormItemDependencyRule retVal = null; - // - if (triggerElement instanceof SingleSelection) { - retVal = new SingleSelectionTriggerdDependencyRule((SingleSelection) triggerElement, (String) triggerValue, targets, type); - } else if (triggerElement instanceof MultipleSelectionElement) { - retVal = new MultiSelectionTriggerdDependencyRule((MultipleSelectionElement) triggerElement, (String) triggerValue, targets, type); - } else if (triggerElement instanceof TextElement) { - retVal = new TextElementTriggerdDependencyRule((TextElement) triggerElement, (String) triggerValue, targets, type); - } else { - throw new AssertException("Form Item of type <" + triggerElement.getClass().getName() + "> not yet supported as TRIGGERELEMENT"); - } - // - return retVal; - } -} diff --git a/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/SingleSelectionTriggerdDependencyRule.java b/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/SingleSelectionTriggerdDependencyRule.java deleted file mode 100644 index 9b071497c3d..00000000000 --- a/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/SingleSelectionTriggerdDependencyRule.java +++ /dev/null @@ -1,68 +0,0 @@ -/** -* OLAT - Online Learning and Training<br> -* http://www.olat.org -* <p> -* Licensed under the Apache License, Version 2.0 (the "License"); <br> -* you may not use this file except in compliance with the License.<br> -* You may obtain a copy of the License at -* <p> -* http://www.apache.org/licenses/LICENSE-2.0 -* <p> -* Unless required by applicable law or agreed to in writing,<br> -* software distributed under the License is distributed on an "AS IS" BASIS, <br> -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> -* See the License for the specific language governing permissions and <br> -* limitations under the License. -* <p> -* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> -* University of Zurich, Switzerland. -* <hr> -* <a href="http://www.openolat.org"> -* OpenOLAT - Online Learning and Training</a><br> -* This file has been modified by the OpenOLAT community. Changes are licensed -* under the Apache 2.0 license as the original file. -* <p> -*/ -package org.olat.core.gui.components.form.flexible.impl.rules; - -import java.util.Set; - -import org.olat.core.gui.components.form.flexible.FormItem; -import org.olat.core.gui.components.form.flexible.FormItemDependencyRule; -import org.olat.core.gui.components.form.flexible.elements.SingleSelection; - -/** - * Description:<br> - * TODO: patrickb Class Description for VisibilityRule - * - * <P> - * Initial Date: 09.02.2007 <br> - * @author patrickb - */ -class SingleSelectionTriggerdDependencyRule extends FormItemDependencyRuleImpl implements FormItemDependencyRule { - - /** - * for type - * <ul> - * <li>{@link FormItemDependencyRuleImpl#MAKE_INVISIBLE}</li> - * <li>{@link FormItemDependencyRuleImpl#MAKE_VISIBLE}</li> - * <li>{@link FormItemDependencyRuleImpl#MAKE_READONLY}</li> - * <li>{@link FormItemDependencyRuleImpl#MAKE_WRITABLE}</li> - * - * @param triggerElement - * @param triggerValue - * @param targets - * @param type - */ - public SingleSelectionTriggerdDependencyRule(SingleSelection triggerElement, String triggerValue, Set<FormItem> targets, int type) { - super(triggerElement, triggerValue, targets, type); - } - - @Override - protected boolean doesTrigger() { - SingleSelection singlsel =(SingleSelection)this.triggerElement; - String selected = singlsel.getSelectedKey(); - return selected.equals(this.triggerVal); - } - -} diff --git a/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/TextElementTriggerdDependencyRule.java b/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/TextElementTriggerdDependencyRule.java deleted file mode 100644 index 5e70fcceed8..00000000000 --- a/src/main/java/org/olat/core/gui/components/form/flexible/impl/rules/TextElementTriggerdDependencyRule.java +++ /dev/null @@ -1,68 +0,0 @@ -/** -* OLAT - Online Learning and Training<br> -* http://www.olat.org -* <p> -* Licensed under the Apache License, Version 2.0 (the "License"); <br> -* you may not use this file except in compliance with the License.<br> -* You may obtain a copy of the License at -* <p> -* http://www.apache.org/licenses/LICENSE-2.0 -* <p> -* Unless required by applicable law or agreed to in writing,<br> -* software distributed under the License is distributed on an "AS IS" BASIS, <br> -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> -* See the License for the specific language governing permissions and <br> -* limitations under the License. -* <p> -* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> -* University of Zurich, Switzerland. -* <hr> -* <a href="http://www.openolat.org"> -* OpenOLAT - Online Learning and Training</a><br> -* This file has been modified by the OpenOLAT community. Changes are licensed -* under the Apache 2.0 license as the original file. -* <p> -*/ -package org.olat.core.gui.components.form.flexible.impl.rules; - -import java.util.Set; - -import org.olat.core.gui.components.form.flexible.FormItem; -import org.olat.core.gui.components.form.flexible.FormItemDependencyRule; -import org.olat.core.gui.components.form.flexible.elements.TextElement; - -/** - * Description:<br> - * TODO: patrickb Class Description for TextElementTriggerdDependencyRule - * - * <P> - * Initial Date: 11.02.2007 <br> - * @author patrickb - */ -class TextElementTriggerdDependencyRule extends FormItemDependencyRuleImpl implements FormItemDependencyRule { - - public TextElementTriggerdDependencyRule(TextElement triggerElement, String triggerValue, Set<FormItem> targets, int type) { - super(triggerElement, triggerValue, targets, type); - } - - /** - * @see org.olat.core.gui.components.form.flexible.rules.FormItemDependencyRuleImpl#doesTrigger() - */ - @Override - protected boolean doesTrigger() { - TextElement te = (TextElement)this.triggerElement; - String val = te.getValue(); - // - if(val == null && triggerVal == null){ - //triggerVal and val are NULL -> true - return true; - }else if(triggerVal != null){ - //triggerVal can be compared - return triggerVal.equals(val); - }else{ - // triggerVal is null but val is not null -> false - return false; - } - } - -} diff --git a/src/main/java/org/olat/core/util/i18n/ui/I18nConfigController.java b/src/main/java/org/olat/core/util/i18n/ui/I18nConfigController.java index 0485dcf8481..ea0f792c053 100644 --- a/src/main/java/org/olat/core/util/i18n/ui/I18nConfigController.java +++ b/src/main/java/org/olat/core/util/i18n/ui/I18nConfigController.java @@ -203,13 +203,7 @@ class I18nConfigController extends FormBasicController { i18nModule.setEnabledLanguageKeys(enabledLangKeys); } else if (source == createLanguageLink) { - // Show new language sub form in an overlay window - subCtr = new I18nConfigSubNewLangController(ureq, getWindowControl()); - listenTo(subCtr); - cmc = new CloseableModalController(getWindowControl(), "close", subCtr.getInitialComponent()); - cmc.activate(); - listenTo(cmc); - + doNewLanguage(ureq); } else if (source == deleteLanguageLink) { // Show delete language sub form in an overlay window subCtr = new I18nConfigSubDeleteLangController(ureq, getWindowControl()); @@ -249,6 +243,7 @@ class I18nConfigController extends FormBasicController { * @see org.olat.core.gui.control.DefaultController#event(org.olat.core.gui.UserRequest, * org.olat.core.gui.control.Controller, org.olat.core.gui.control.Event) */ + @Override public void event(UserRequest ureq, Controller source, Event event) { if (source == cmc) { // must be close event @@ -271,4 +266,19 @@ class I18nConfigController extends FormBasicController { protected void doDispose() { // nothing to dispose, sub controller autodisposed by basic controller } + + /** + * Show new language sub form in an overlay window + * + * @param ureq The user request + */ + private void doNewLanguage(UserRequest ureq) { + subCtr = new I18nConfigSubNewLangController(ureq, getWindowControl()); + listenTo(subCtr); + + String title = translate("configuration.management.create.title"); + cmc = new CloseableModalController(getWindowControl(), "close", subCtr.getInitialComponent(), true, title); + cmc.activate(); + listenTo(cmc); + } } diff --git a/src/main/java/org/olat/core/util/i18n/ui/I18nConfigSubNewLangController.java b/src/main/java/org/olat/core/util/i18n/ui/I18nConfigSubNewLangController.java index ccd78fd9d2c..1313804f7e4 100644 --- a/src/main/java/org/olat/core/util/i18n/ui/I18nConfigSubNewLangController.java +++ b/src/main/java/org/olat/core/util/i18n/ui/I18nConfigSubNewLangController.java @@ -24,22 +24,17 @@ */ package org.olat.core.util.i18n.ui; -import java.util.HashSet; import java.util.Locale; -import java.util.Set; import org.olat.core.dispatcher.DispatcherModule; import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.form.flexible.FormItem; import org.olat.core.gui.components.form.flexible.FormItemContainer; -import org.olat.core.gui.components.form.flexible.FormItemDependencyRule; import org.olat.core.gui.components.form.flexible.elements.FormLink; import org.olat.core.gui.components.form.flexible.elements.TextElement; import org.olat.core.gui.components.form.flexible.impl.FormBasicController; import org.olat.core.gui.components.form.flexible.impl.FormEvent; import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer; -import org.olat.core.gui.components.form.flexible.impl.rules.FormItemDependencyRuleImpl; -import org.olat.core.gui.components.form.flexible.impl.rules.RulesFactory; import org.olat.core.gui.components.link.Link; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.Event; @@ -84,9 +79,10 @@ class I18nConfigSubNewLangController extends FormBasicController { * @param control */ protected I18nConfigSubNewLangController(UserRequest ureq, WindowControl control) { - super(ureq, control, LAYOUT_DEFAULT); - if (!i18nModule.isTransToolEnabled()) { throw new AssertException( - "New languages can only be created when the translation tool is enabled and the translation tool source pathes are configured in the olat.properties"); } + super(ureq, control); + if (!i18nModule.isTransToolEnabled()) { + throw new AssertException("New languages can only be created when the translation tool is enabled and the translation tool source pathes are configured in the olat.properties"); + } initForm(ureq); } @@ -98,7 +94,6 @@ class I18nConfigSubNewLangController extends FormBasicController { protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { // New language elements: // A title, displayed in fieldset - setFormTitle("configuration.management.create.title"); String[] args = new String[] { "<a href='http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt' target='_blank'><i class='o_icon o_icon_link_extern'> </i> ISO639</a>", "<a href='http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html' target='_blank'><i class='o_icon o_icon_link_extern'> </i> ISO3166</a>" }; setFormDescription("configuration.management.create.description", args); @@ -124,33 +119,7 @@ class I18nConfigSubNewLangController extends FormBasicController { newVariant.setExampleKey("configuration.management.create.variant.example", null); newVariant.setRegexMatchCheck("[A-Za-z0-9_]*", "configuration.management.create.variant.error"); newVariant.setDisplaySize(10); - // Rule1: hide variant when country is empty - Set<FormItem> hideItems = new HashSet<FormItem>(); - RulesFactory.createHideRule(newCountry, "", hideItems, formLayout); - hideItems.add(newVariant); - // Rule 2: show variant when country is not empty - FormItemDependencyRule showRule = new FormItemDependencyRuleImpl(newCountry, ".{2}", hideItems, FormItemDependencyRuleImpl.MAKE_VISIBLE) { - @Override - protected boolean doesTrigger() { - TextElement te = (TextElement) this.triggerElement; - String val = te.getValue(); - // - if (val == null && triggerVal == null) { - // triggerVal and val are NULL -> true - return true; - } else if (val != null) { - // val can be compared - String stringTriggerValString = (String) triggerVal; - boolean matches = val.matches(stringTriggerValString); - return matches; - } else { - // triggerVal is null but val is not null -> false - return false; - } - } - }; - formLayout.addDependencyRule(showRule); - // + newVariant.setVisible(false); // Language name and translator data newTranslatedInEnglish = uifactory.addTextElement("configuration.management.create.inEnglish", "configuration.management.create.inEnglish", 255, "", formLayout); @@ -246,17 +215,17 @@ class I18nConfigSubNewLangController extends FormBasicController { newCountry.setValue(""); newVariant.setValue(""); } + + boolean visible = val != null && val.matches(".{2}"); + newVariant.setVisible(visible); } if (!newVariant.isEmpty() && newCountry.isEmpty()) { newCountry.setErrorKey("configuration.management.create.variant.error.noCountry", null); } } - /** - * @see org.olat.core.gui.components.form.flexible.impl.FormBasicController#doDispose() - */ @Override protected void doDispose() { - // nothing to dispose + // } } diff --git a/src/main/java/org/olat/course/condition/ConditionConfigEasyController.java b/src/main/java/org/olat/course/condition/ConditionConfigEasyController.java index 5182125d613..db95117a18b 100644 --- a/src/main/java/org/olat/course/condition/ConditionConfigEasyController.java +++ b/src/main/java/org/olat/course/condition/ConditionConfigEasyController.java @@ -29,15 +29,12 @@ import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Set; import org.olat.core.gui.UserRequest; -import org.olat.core.gui.components.form.flexible.DependencyRuleApplayable; import org.olat.core.gui.components.form.flexible.FormItem; import org.olat.core.gui.components.form.flexible.FormItemContainer; -import org.olat.core.gui.components.form.flexible.FormItemDependencyRule; import org.olat.core.gui.components.form.flexible.elements.FormLink; import org.olat.core.gui.components.form.flexible.elements.IntegerElement; import org.olat.core.gui.components.form.flexible.elements.MultipleSelectionElement; @@ -48,7 +45,6 @@ import org.olat.core.gui.components.form.flexible.impl.FormEvent; import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer; import org.olat.core.gui.components.form.flexible.impl.elements.FormLinkImpl; import org.olat.core.gui.components.form.flexible.impl.elements.JSDateChooser; -import org.olat.core.gui.components.form.flexible.impl.rules.RulesFactory; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.Event; import org.olat.core.gui.control.WindowControl; @@ -92,12 +88,15 @@ public class ConditionConfigEasyController extends FormBasicController implement private Condition validatedCondition; private CourseEditorEnv courseEditorEnv; private List<CourseNode> nodeIdentList; - //private FormReset reset; - private MultipleSelectionElement coachExclusive, assessmentMode; + private MultipleSelectionElement coachExclusive; + private MultipleSelectionElement assessmentMode; private JSDateChooser fromDate; private JSDateChooser toDate; - private FormItemContainer dateSubContainer, groupSubContainer, assessSubContainer; - private FormLayoutContainer areaChooseSubContainer, groupChooseSubContainer; + private FormItemContainer dateSubContainer; + private FormItemContainer groupSubContainer; + private FormItemContainer assessSubContainer; + private FormLayoutContainer areaChooseSubContainer; + private FormLayoutContainer groupChooseSubContainer; private MultipleSelectionElement dateSwitch; private StaticTextElement easyGroupList; private FormLink chooseGroupsLink; @@ -176,15 +175,246 @@ public class ConditionConfigEasyController extends FormBasicController implement /* * my instance variables, these data is used by form items to initialise */ - this.validatedCondition = cloneCondition(cond); - if (this.validatedCondition == null) throw new OLATRuntimeException( - "CondititionEditController called with a NULL condition", - new IllegalArgumentException() - ); + validatedCondition = cloneCondition(cond); + if (validatedCondition == null) { + throw new OLATRuntimeException("CondititionEditController called with a NULL condition", new IllegalArgumentException()); + } this.courseEditorEnv = env; this.nodeIdentList = nodeIdentList; initForm(ureq); + updateUI(); + } + + @Override + protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { + // or blocked for learner + coachExclusive = uifactory.addCheckboxesHorizontal("coachExclusive", null, formLayout, new String[] { "ison" }, new String[] { translate("form.easy.coachExclusive") }); + coachExclusive.setElementCssClass("o_sel_condition_coach_exclusive"); + coachExclusive.addActionListener(FormEvent.ONCLICK); + if(validatedCondition.isEasyModeCoachesAndAdmins()) { + coachExclusive.select("ison", true); + } + + initFromToDateChooser(formLayout); + initEasyGroupAreaChoosers(formLayout); + initAssessmentSwitch(formLayout); + // shibboleth attributes + boolean enableShibbolethEasyConfig = shibbolethModule.isEnableShibbolethCourseEasyConfig(); + if(enableShibbolethEasyConfig) { + initAttributeSwitch(formLayout, ureq); + } + flc.contextPut("shibbolethEnabled", Boolean.valueOf(enableShibbolethEasyConfig)); + + assessmentMode = uifactory.addCheckboxesHorizontal("assessmentMode", null, formLayout, new String[] { "ison" }, new String[] { translate("form.easy.assessmentMode") }); + if(validatedCondition.isAssessmentMode()) { + assessmentMode.select("ison", true); + } + assessmentMode.addActionListener(FormEvent.ONCLICK); + assessmentMode.setVisible(assessmentModule.isAssessmentModeEnabled()); + + applyRulesForCoach = uifactory.addCheckboxesHorizontal("applyRulesForCoach", null, formLayout, new String[] { "ison" }, new String[] { translate("form.easy.applyRulesForCoach") }); + applyRulesForCoach.setVisible(isDateGroupAssessmentOrAttributeSwitchOnOrAssessmentModeOn()); + // note that in the condition this rule is saved with the opposite meaning: + // true when coach and admins always have access, false when rule should apply also to them + if (!validatedCondition.isEasyModeAlwaysAllowCoachesAndAdmins()) { + applyRulesForCoach.select("ison", true); + } + + // the submit button + uifactory.addFormSubmitButton("subm", "submit", formLayout); + validateGroupFields(); + } + + private void initFromToDateChooser(FormItemContainer formLayout) { + /* + * yes / no switch if a date.time constraint is defined + */ + dateSubContainer = FormLayoutContainer.createDefaultFormLayout("dateSubContainer", getTranslator()); + formLayout.add(dateSubContainer); + + fromDate = new JSDateChooser("fromDate", getLocale()); + fromDate.setLabel("form.easy.bdate", null); + fromDate.setDate(ConditionDateFormatter.parse(validatedCondition.getEasyModeBeginDate())); + fromDate.setExampleKey("form.easy.example.bdate", null); + fromDate.setDateChooserTimeEnabled(true); + fromDate.setDisplaySize(fromDate.getExampleDateString().length()); + dateSubContainer.add(fromDate); + + toDate = new JSDateChooser("toDate", getLocale()); + toDate.setLabel("form.easy.edate", null); + toDate.setDate(ConditionDateFormatter.parse(validatedCondition.getEasyModeEndDate())); + toDate.setExampleKey("form.easy.example.edate", null); + toDate.setDateChooserTimeEnabled(true); + toDate.setDisplaySize(toDate.getExampleDateString().length()); + dateSubContainer.add(toDate); + + dateSwitch = uifactory.addCheckboxesHorizontal("dateSwitch", null, formLayout, new String[] { "ison" }, new String[] { translate("form.easy.dateSwitch") }); + if (fromDate.getDate() != null || toDate.getDate() != null) { + dateSwitch.select("ison", true); + } + dateSwitch.addActionListener(FormEvent.ONCLICK); + } + + /** + * @param formLayout + * @param listener + */ + private void initEasyGroupAreaChoosers(FormItemContainer formLayout) { + + groupSubContainer = FormLayoutContainer.createBareBoneFormLayout("groupSubContainer", getTranslator()); + formLayout.add(groupSubContainer); + + List<Long> groupKeyList = validatedCondition.getEasyModeGroupAccessIdList(); + String groupInitVal = getGroupNames(groupKeyList); + List<Long> areaKeyList = validatedCondition.getEasyModeGroupAreaAccessIdList(); + String areaInitVal = getAreaNames(areaKeyList); + + groupSwitch = uifactory.addCheckboxesHorizontal("groupSwitch", null, formLayout, new String[] { "ison" }, new String[] { translate("form.easy.groupSwitch") }); + groupSwitch.setElementCssClass("o_sel_condition_groups"); + // initialize selection + if (!groupKeyList.isEmpty() || !areaKeyList.isEmpty()) { + groupSwitch.select("ison", true); + } + groupSwitch.addActionListener(FormEvent.ONCLICK); + + //groups + groupChooseSubContainer = FormLayoutContainer.createDefaultFormLayout("groupChooseSubContainer", getTranslator()); + groupSubContainer.add(groupChooseSubContainer); + + easyGroupList = uifactory.addStaticTextElement("groupList", "form.easy.group", groupInitVal, groupChooseSubContainer); + easyGroupList.setUserObject(groupKeyList); + + chooseGroupsLink = uifactory.addFormLink("choose", groupChooseSubContainer, "o_form_groupchooser"); + chooseGroupsLink.setElementCssClass("o_sel_condition_choose_groups"); + createGroupsLink = uifactory.addFormLink("create", groupChooseSubContainer, "o_form_groupchooser"); + createGroupsLink.setElementCssClass("o_sel_condition_create_groups"); + + //areas + areaChooseSubContainer = FormLayoutContainer.createDefaultFormLayout("areaChooseSubContainer", getTranslator()); + groupSubContainer.add(areaChooseSubContainer); + + easyAreaList = uifactory.addStaticTextElement("groupList", "form.easy.area", areaInitVal, areaChooseSubContainer); + easyAreaList.setUserObject(areaKeyList); + + chooseAreasLink = uifactory.addFormLink("choose", areaChooseSubContainer, "o_form_groupchooser"); + createAreasLink = uifactory.addFormLink("create", areaChooseSubContainer, "o_form_groupchooser"); + + updateGroupsAndAreasCheck(); + } + + private void initAttributeSwitch(FormItemContainer formLayout, UserRequest ureq) { + + String[] values = new String[]{ translate("form.easy.attributeSwitch") }; + attributeSwitch = uifactory.addCheckboxesHorizontal("attributeSwitch", null, formLayout, new String[] { "ison" }, values); + attributeSwitch.select("ison", validatedCondition.getAttributeConditions() != null); + // register for on click event to hide/disable other elements + attributeSwitch.addActionListener(FormEvent.ONCLICK); + // rules are later added + + // add attribute connector: AND or OR + final String[] attributebconnectorValues = new String[] { translate("form.easy.attributebconnector.and"), translate("form.easy.attributebconnector.or") }; + attributeBconnector = uifactory.addRadiosHorizontal("attributeBconnector", "form.easy.attributebconnector", formLayout, new String[] { BCON_VAL_AND, BCON_VAL_OR }, attributebconnectorValues); + if(validatedCondition.isConditionsConnectorIsAND()){ + attributeBconnector.select(BCON_VAL_AND, true); + } else { + attributeBconnector.select(BCON_VAL_OR, true); + } + + // add attribute condition rows + attribteRowAdderSubform = new AttributeEasyRowAdderController(ureq, getWindowControl(), mainForm); + flc.add(attribteRowAdderSubform.getFormItem()); + + listenTo(attribteRowAdderSubform); + flc.put("attribteRowAdderSubform", attribteRowAdderSubform.getInitialComponent()); + if (validatedCondition.getAttributeConditions() != null && !validatedCondition.getAttributeConditions().isEmpty()) { + attribteRowAdderSubform.setAttributeConditions(validatedCondition.getAttributeConditions()); + } + } + + private void initAssessmentSwitch(FormItemContainer formLayout) { + assessSubContainer = FormLayoutContainer.createDefaultFormLayout("assessSubContainer", getTranslator()); + formLayout.add(assessSubContainer); + + Translator translator = getTranslator(); + + final String[] assessmentSwitchKeys = new String[] { NODEPASSED_VAL_PASSED, NODEPASSED_VAL_SCORE }; + final String[] assessmentSwitchValues = new String[] { translator.translate("form.easy.assessmentSwitch.passed"), + translator.translate("form.easy.assessmentSwitch.score") }; + + String nodePassedInitVal = validatedCondition.getEasyModeNodePassedId(); + String cutInitStrValue = validatedCondition.getEasyModeCutValue(); + int cutInitValue = 0; + + assessmentSwitch = uifactory.addCheckboxesHorizontal("assessmentSwitch", null, formLayout, new String[] { "ison" }, new String[] { translate("form.easy.assessmentSwitch") }); + assessmentSwitch.addActionListener(FormEvent.ONCLICK); + + + boolean selectedNodeIsInList = false; + List<String> keysList = new ArrayList<>(); + List<String> valuesList = new ArrayList<>(); + if (nodeIdentList.isEmpty()) { + // no nodes to be selected + keysList.add(NO_NODE_SELECTED_IDENTIFYER); + valuesList.add("- " + translator.translate("form.easy.nodePassed.noNodes")); + //disable switch + assessmentSwitch.setEnabled(false); + } else { + // there are nodes to be selected + keysList.add(NO_NODE_SELECTED_IDENTIFYER); + valuesList.add("- " + translator.translate("form.easy.nodePassed.select") + " -"); + for (int i = 0; i < nodeIdentList.size(); i++) { + CourseNode courseNode = nodeIdentList.get(i); + keysList.add(courseNode.getIdent()); + valuesList.add(courseNode.getShortName() + " (Id:" + courseNode.getIdent() + ")"); + if (courseNode.getIdent().equals(nodePassedInitVal)) selectedNodeIsInList = true; + } + } + // add dummy value if needed + if (nodePassedInitVal != null && !selectedNodeIsInList) { + keysList.add(DELETED_NODE_IDENTIFYER); + valuesList.add("- " + translator.translate("form.easy.nodePassed.deletedNode") + " -"); + } + final String[] nodePassedKeys = new String[keysList.size()]; + keysList.toArray(nodePassedKeys); + final String[] nodePassedValues = new String[valuesList.size()]; + valuesList.toArray(nodePassedValues); + + nodePassed = uifactory.addDropdownSingleselect("nodePassed", "form.easy.nodePassed", assessSubContainer, nodePassedKeys, nodePassedValues, null); + if (nodePassedInitVal != null) { + if (selectedNodeIsInList) { + nodePassed.select(nodePassedInitVal, true); + } else { + nodePassed.select(DELETED_NODE_IDENTIFYER, true); + } + } else { + nodePassed.select(NO_NODE_SELECTED_IDENTIFYER, true); + } + + assessmentTypeSwitch = uifactory.addRadiosVertical("assessmentTypeSwitch", null, assessSubContainer, + assessmentSwitchKeys, assessmentSwitchValues); + assessmentTypeSwitch.setLabel("form.easy.assessmentSwitch.type", null); + assessmentTypeSwitch.addActionListener(FormEvent.ONCLICK); + + if (nodePassedInitVal != null) { + // has a node configured + if (cutInitStrValue == null) { + // with cut value + assessmentTypeSwitch.select(NODEPASSED_VAL_PASSED, true); + } else { + cutInitValue = Integer.valueOf(cutInitStrValue); + assessmentTypeSwitch.select(NODEPASSED_VAL_SCORE, true); + } + assessmentSwitch.select("ison", true); + assessmentTypeSwitch.setVisible(true); + } else { + assessmentSwitch.uncheckAll(); + assessmentTypeSwitch.setVisible(false); + assessmentTypeSwitch.select(NODEPASSED_VAL_PASSED, true); + } + + cutValue = uifactory.addIntegerElement("cutval", "form.easy.cutValue", cutInitValue, assessSubContainer); + cutValue.setDisplaySize(3); } /** @@ -203,7 +433,7 @@ public class ConditionConfigEasyController extends FormBasicController implement // 1) rule applies also for coach switch - one checkbox // has opposite meaning -> selected is saved as false, and vice versa - if (applyRulesForCoach.getSelectedKeys().size() == 0) { + if (applyRulesForCoach.getSelectedKeys().isEmpty()) { validatedCondition.setEasyModeAlwaysAllowCoachesAndAdmins(true); } else { validatedCondition.setEasyModeAlwaysAllowCoachesAndAdmins(false); @@ -221,6 +451,8 @@ public class ConditionConfigEasyController extends FormBasicController implement validatedCondition.setAttributeConditions(null); validatedCondition.setAttributeConditionsConnectorIsAND(null); validatedCondition.setAssessmentMode(false); + validatedCondition.setEasyModeGroupAccessIdList(null); + validatedCondition.setEasyModeGroupAreaAccessIdList(null); } else { validatedCondition.setEasyModeCoachesAndAdmins(false); // 3) date switch @@ -280,7 +512,7 @@ public class ConditionConfigEasyController extends FormBasicController implement } } else { validatedCondition.setEasyModeNodePassedId(null); - if(nodeIdentList.size()==0) { + if(nodeIdentList.isEmpty()) { assessmentSwitch.setEnabled(false); } } @@ -290,14 +522,14 @@ public class ConditionConfigEasyController extends FormBasicController implement if (attributeSwitch.getSelectedKeys().size() == 1) { List<ExtendedCondition> le = attribteRowAdderSubform.getAttributeConditions(); - if (le.size() < 1) { + if (le.isEmpty()) { // some error(s) occured, don't save anything validatedCondition.setAttributeConditions(null); } else { // add the conditions validatedCondition.setAttributeConditions(le); } - validatedCondition.setAttributeConditionsConnectorIsAND(new Boolean(attributeBconnector.getSelectedKey().equals(BCON_VAL_AND))); + validatedCondition.setAttributeConditionsConnectorIsAND(Boolean.valueOf(attributeBconnector.getSelectedKey().equals(BCON_VAL_AND))); } else { validatedCondition.setAttributeConditions(null); @@ -317,8 +549,6 @@ public class ConditionConfigEasyController extends FormBasicController implement /* * condition is updated */ - - // Inform all listeners about the changed condition fireEvent(ureq, Event.CHANGED_EVENT); } @@ -329,162 +559,63 @@ public class ConditionConfigEasyController extends FormBasicController implement validateGroupFields(); } } - - @Override - protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) { - if (source == chooseGroupsLink) { - removeAsListenerAndDispose(cmc); - removeAsListenerAndDispose(groupChooseC); - - List<Long> groupKeys = getKeys(easyGroupList); - groupChooseC = new GroupSelectionController(ureq, getWindowControl(), true, - courseEditorEnv.getCourseGroupManager(), groupKeys); - listenTo(groupChooseC); - - cmc = new CloseableModalController( - getWindowControl(), "close", groupChooseC.getInitialComponent(), - true, getTranslator().translate("popupchoosegroups")); - listenTo(cmc); - cmc.activate(); - } else if (source == createGroupsLink) { - removeAsListenerAndDispose(cmc); - removeAsListenerAndDispose(groupCreateCtlr); - - OLATResource courseResource = courseEditorEnv.getCourseGroupManager().getCourseResource(); - RepositoryEntry courseRe = RepositoryManager.getInstance().lookupRepositoryEntry(courseResource, false); - groupCreateCtlr = new NewBGController(ureq, getWindowControl(), courseRe, true, null); - listenTo(groupCreateCtlr); - cmc = new CloseableModalController(getWindowControl(), "close", groupCreateCtlr.getInitialComponent()); - listenTo(cmc); - cmc.activate(); - } else if (source == chooseAreasLink) { - removeAsListenerAndDispose(cmc); - removeAsListenerAndDispose(areaChooseC); - - areaChooseC = new AreaSelectionController(ureq, getWindowControl(), true, - courseEditorEnv.getCourseGroupManager(), getKeys(easyAreaList)); - listenTo(areaChooseC); - - cmc = new CloseableModalController( - getWindowControl(), "close", areaChooseC.getInitialComponent(), - true, getTranslator().translate("popupchooseareas")); - listenTo(cmc); - cmc.activate(); - } else if (source == createAreasLink) { - removeAsListenerAndDispose(cmc); - removeAsListenerAndDispose(areaCreateCtlr); - - OLATResource courseResource = courseEditorEnv.getCourseGroupManager().getCourseResource(); - areaCreateCtlr = new NewAreaController(ureq, getWindowControl(), courseResource, true, null); - listenTo(areaCreateCtlr); - - cmc = new CloseableModalController(getWindowControl(), "close",areaCreateCtlr.getInitialComponent()); - listenTo(cmc); - cmc.activate(); - } else if (source == fixGroupError) { - // user wants to fix problem with fixing group error link e.g. create one - // or more group at once. - String[] csvGroupName = (String[]) fixGroupError.getUserObject(); - OLATResource courseResource = courseEditorEnv.getCourseGroupManager().getCourseResource(); - RepositoryEntry courseRe = RepositoryManager.getInstance().lookupRepositoryEntry(courseResource, false); - removeAsListenerAndDispose(groupCreateCtlr); - groupCreateCtlr = new NewBGController(ureq, getWindowControl(), courseRe, true, csvGroupName[0]); - listenTo(groupCreateCtlr); - - removeAsListenerAndDispose(cmc); - cmc = new CloseableModalController(getWindowControl(), "close", groupCreateCtlr.getInitialComponent()); - listenTo(cmc); - cmc.activate(); - } else if (source == fixAreaError) { - /* - * user wants to fix problem with fixing area error link e.g. create one - * or more areas at once. - */ - String[] csvAreaName = (String[]) fixAreaError.getUserObject(); - OLATResource courseResource = courseEditorEnv.getCourseGroupManager().getCourseResource(); - removeAsListenerAndDispose(areaCreateCtlr); - areaCreateCtlr = new NewAreaController(ureq, getWindowControl(), courseResource, true, csvAreaName[0]); - listenTo(areaCreateCtlr); - - removeAsListenerAndDispose(cmc); - cmc = new CloseableModalController(getWindowControl(), "close", areaCreateCtlr.getInitialComponent()); - listenTo(cmc); - cmc.activate(); - } - } - + @Override protected void event(UserRequest ureq, Controller source, org.olat.core.gui.control.Event event) { - if (source == groupChooseC) { - if (Event.DONE_EVENT == event) { + doGroupChoosed(ureq, groupChooseC.getSelectedKeys()); cmc.deactivate(); - List<Long> groupKeys = groupChooseC.getSelectedKeys(); - easyGroupList.setUserObject(groupKeys); - easyGroupList.setValue(getGroupNames(groupKeys)); - validateGroupFields(); - easyGroupList.getRootForm().submit(ureq); } else if (event == Event.CANCELLED_EVENT) { cmc.deactivate(); - } else if (event == Event.CHANGED_EVENT) { - //a group was created within from within the chooser } - - } else if (source == areaChooseC) { - + } else if (source == areaChooseC) { if (event == Event.DONE_EVENT) { - + doAreaChoosed(ureq, areaChooseC.getSelectedKeys()); cmc.deactivate(); - List<Long> areaKeys = areaChooseC.getSelectedKeys(); - easyAreaList.setUserObject(areaKeys); - easyAreaList.setValue(this.getAreaNames(areaKeys)); - validateGroupFields(); - easyAreaList.getRootForm().submit(ureq); - } else if (event == Event.CANCELLED_EVENT) { cmc.deactivate(); - } else if (event == Event.CHANGED_EVENT) { - //an area was created within from within the chooser } - } else if (source == groupCreateCtlr) { cmc.deactivate(); if (event == Event.DONE_EVENT) { - List<Long> c = new ArrayList<Long>(); - c.addAll(getKeys(easyGroupList)); - if (fixGroupError != null && fixGroupError.getUserObject() != null) { - c.removeAll(Arrays.asList((String[])fixGroupError.getUserObject())); - } - c.addAll(groupCreateCtlr.getCreatedGroupKeys()); - easyGroupList.setValue(getGroupNames(c)); - easyGroupList.setUserObject(c); - easyGroupList.getRootForm().submit(ureq); - validateGroupFields(); - - if (!groupCreateCtlr.getCreatedGroupKeys().isEmpty()) { - singleUserEventCenter.fireEventToListenersOf(new MultiUserEvent("changed"), groupConfigChangeEventOres); - } + doGroupCreated(ureq, groupCreateCtlr.getCreatedGroupKeys()); } } else if (source == areaCreateCtlr) { cmc.deactivate(); if (event == Event.DONE_EVENT) { - List<Long> c = new ArrayList<Long>(); - c.addAll(getKeys(easyAreaList)); - if (fixAreaError!= null && fixAreaError.getUserObject() != null) { - c.removeAll(Arrays.asList((String[])fixAreaError.getUserObject())); - } - c.addAll(areaCreateCtlr.getCreatedAreaKeys()); - - easyAreaList.setValue(getAreaNames(c)); - easyAreaList.setUserObject(c); - easyAreaList.getRootForm().submit(ureq); - validateGroupFields(); - - if (!areaCreateCtlr.getCreatedAreaKeys().isEmpty()) { - singleUserEventCenter.fireEventToListenersOf(new MultiUserEvent("changed"), groupConfigChangeEventOres); - } + doAreaCreated(ureq, areaCreateCtlr.getCreatedAreaKeys()); + } + } + } + + @Override + protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) { + if (source == chooseGroupsLink) { + doChooseGroup(ureq); + } else if (source == createGroupsLink) { + doCreateGroup(ureq); + } else if (source == chooseAreasLink) { + doChooseArea(ureq); + } else if (source == createAreasLink) { + doCreateArea(ureq); + } else if (source == fixGroupError) { + doFixGroupError(ureq); + } else if (source == fixAreaError) { + doFixArea(ureq); + } else { + if(coachExclusive == source && coachExclusive.isAtLeastSelected(1)) { + setBlockedForLearner(); + } else if(dateSwitch == source && !dateSwitch.isAtLeastSelected(1)) { + disableDates(); + } else if(assessmentSwitch == source && !assessmentSwitch.isAtLeastSelected(1)) { + disableAssessment(); + } else if(groupSwitch == source && !groupSwitch.isAtLeastSelected(1)) { + disableGroup(); + } else if(attributeSwitch == source && !attributeSwitch.isAtLeastSelected(1)) { + disableAttribute(); } + updateUI(); } } @@ -580,7 +711,7 @@ public class ConditionConfigEasyController extends FormBasicController implement // check whether groups exist activeGroupSelection = getKeys(easyGroupList); - Set<Long> missingGroups = new HashSet<Long>(); + Set<Long> missingGroups = new HashSet<>(); List<BusinessGroupShort> existingGroups = businessGroupService.loadShortBusinessGroups(activeGroupSelection); a_a: for(Long activeGroupKey:activeGroupSelection) { @@ -592,15 +723,15 @@ public class ConditionConfigEasyController extends FormBasicController implement missingGroups.add(activeGroupKey); } - if (missingGroups.size() > 0) { + if (!missingGroups.isEmpty()) { retVal = false; String labelKey = missingGroups.size() == 1 ? "error.notfound.name" : "error.notfound.names"; String csvMissGrps = toString(missingGroups); String[] params = new String[] { "-", csvMissGrps }; // create error with link to fix it - String vc_errorPage = velocity_root + "/erroritem.html"; - FormLayoutContainer errorGroupItemLayout = FormLayoutContainer.createCustomFormLayout( - "errorgroupitem", getTranslator(), vc_errorPage); + String vcErrorPage = velocity_root + "/erroritem.html"; + FormLayoutContainer errorGroupItemLayout = FormLayoutContainer + .createCustomFormLayout("errorgroupitem", getTranslator(), vcErrorPage); groupChooseSubContainer.setErrorComponent(errorGroupItemLayout, this.flc); // FIXING LINK ONLY IF A DEFAULTCONTEXT EXISTS @@ -634,7 +765,7 @@ public class ConditionConfigEasyController extends FormBasicController implement // check whether areas exist activeAreaSelection = getKeys(easyAreaList); - List<Long> missingAreas = new ArrayList<Long>(); + List<Long> missingAreas = new ArrayList<>(); List<BGArea> cnt = areaManager.loadAreas(activeAreaSelection); a_a: for(Long activeAreaKey:activeAreaSelection) { @@ -646,16 +777,16 @@ public class ConditionConfigEasyController extends FormBasicController implement missingAreas.add(activeAreaKey); } - if (missingAreas.size() > 0) { + if (!missingAreas.isEmpty()) { retVal = false; String labelKey = missingAreas.size() == 1 ? "error.notfound.name" : "error.notfound.names"; String csvMissAreas = toString(missingAreas); String[] params = new String[] { "-", csvMissAreas }; // create error with link to fix it - String vc_errorPage = velocity_root + "/erroritem.html"; - FormLayoutContainer errorAreaItemLayout = FormLayoutContainer.createCustomFormLayout( - "errorareaitem", getTranslator(), vc_errorPage); + String vcErrorPage = velocity_root + "/erroritem.html"; + FormLayoutContainer errorAreaItemLayout = FormLayoutContainer + .createCustomFormLayout("errorareaitem", getTranslator(), vcErrorPage); areaChooseSubContainer.setErrorComponent(errorAreaItemLayout, this.flc); // FXINGIN LINK ONLY IF DEFAULT CONTEXT EXISTS @@ -698,13 +829,13 @@ public class ConditionConfigEasyController extends FormBasicController implement } return retVal; } + /** - * @param retVal * @return */ private boolean validateAttibuteFields() { boolean retVal = true; - if (attributeSwitch.getSelectedKeys().size() == 1&&attribteRowAdderSubform.hasError()) { + if (attributeSwitch.getSelectedKeys().size() == 1 && attribteRowAdderSubform.hasError()) { attributeSwitch.setErrorKey("form.easy.error.attribute", null); retVal = false; return retVal; @@ -713,65 +844,6 @@ public class ConditionConfigEasyController extends FormBasicController implement return retVal; } - /** - * @see org.olat.core.gui.components.form.flexible.impl.FormBasicController#initForm(org.olat.core.gui.components.form.flexible.FormItemContainer, - * org.olat.core.gui.control.Controller, org.olat.core.gui.UserRequest) - */ - @Override - protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { - - addCoachExclusive(formLayout); - addFromToDateChooser(formLayout); - addEasyGroupAreaChoosers(formLayout); - addAssessmentSwitch(formLayout); - // - if(shibbolethModule.isEnableShibbolethCourseEasyConfig()) { - addAttributeSwitch(formLayout, ureq); - } - flc.contextPut("shibbolethEnabled", new Boolean(shibbolethModule.isEnableShibbolethCourseEasyConfig())); - addAssessmentMode(formLayout); - addApplyRulesForTutorsToo(formLayout); - - - // add rules - addRules(formLayout); - - // the submit button - uifactory.addFormSubmitButton("subm", "submit", formLayout); - validateGroupFields(); - } - - private void addAttributeSwitch(FormItemContainer formLayout, UserRequest ureq) { - /* - * yes / no chooser defines if learner do not see the building block at all - */ - String[] values = new String[]{ translate("form.easy.attributeSwitch") }; - attributeSwitch = uifactory.addCheckboxesHorizontal("attributeSwitch", null, formLayout, new String[] { "ison" }, values); - attributeSwitch.select("ison", validatedCondition.getAttributeConditions() != null); - // register for on click event to hide/disable other elements - attributeSwitch.addActionListener(FormEvent.ONCLICK); - // rules are later added - - // add attribute connector: AND or OR - final String[] attributebconnectorValues = new String[] { translate("form.easy.attributebconnector.and"), translate("form.easy.attributebconnector.or") }; - attributeBconnector = uifactory.addRadiosHorizontal("attributeBconnector", "form.easy.attributebconnector", formLayout, new String[] { BCON_VAL_AND, BCON_VAL_OR }, attributebconnectorValues); - if(validatedCondition.isConditionsConnectorIsAND()){ - attributeBconnector.select(BCON_VAL_AND, true); - } else { - attributeBconnector.select(BCON_VAL_OR, true); - } - - // add attribute condition rows - attribteRowAdderSubform = new AttributeEasyRowAdderController(ureq, getWindowControl(), mainForm); - flc.add(attribteRowAdderSubform.getFormItem()); - - listenTo(attribteRowAdderSubform); - flc.put("attribteRowAdderSubform", attribteRowAdderSubform.getInitialComponent()); - if (validatedCondition.getAttributeConditions() != null && validatedCondition.getAttributeConditions().size() > 0) { - attribteRowAdderSubform.setAttributeConditions(validatedCondition.getAttributeConditions()); - } - } - /** * Check if any of the date/group/assessment/attributes switch is ON. * @return @@ -784,548 +856,105 @@ public class ConditionConfigEasyController extends FormBasicController implement || (assessmentMode.isEnabled() && assessmentMode.isAtLeastSelected(1)); } - /** - * Show applyRulesForCoach depending on isDateGroupAssessmentOAttributeSwitchOn state. - */ - private void showOrHideApplyRulesForCoach() { - if(isDateGroupAssessmentOrAttributeSwitchOnOrAssessmentModeOn()) { - applyRulesForCoach.setVisible(true); - } else { - applyRulesForCoach.setVisible(false); - } - } - - /** - * you may find here now the complexest rule set ever use in OLAT<br> - * This form has a 5 switches<br> - * <ul> - * <li>[] 1 Learners only</li> - * <li>[] 2 Date dependent</li> - * <li>[] 3 Group dependent</li> - * <li>[] 4 Assess dependent</li> - * <li>[] 5 Apply rules also to coaches</li> - * </ul> - * enable [1] this greys out all others<br> - * if one of [2] [3] or [4] is selected -> [5] becomes selectable<br> - * selecting [2] [3] or [4] opens their respective subconfiguration<br> - * "[2] date dependent" shows an end and startdate where at least one must be - * selected and the start date must be before the enddate.<br> - * "[3] group dependent" shows a group or area input field. which takes group - * or area names comma separated. the form evaluates if the areas or groups - * exists, and if not, a quick fix is provided to create the missing groups/areas. - * furthermore there is a "choose" button to choose groups/areas. This choose - * button is named "create" if there are no groups or areas to choose from. If - * create is clicked a create group/area workflow is started directly. If some - * comma separated values are in the input field, it allows to create them at - * once. At least an area or groupname must be specified, and all the specified - * names must exist.<br> - * "[4] assessment " allows to choose a node and to define a cut value or if - * it should be checked for passed.<br> - * To accomplish all the hiding, disabling, enabling, resetting to initial values - * the following rules are added. this may look confusing, and it is confusing. - * It took quite some days and testing until to get it right. - * @param formLayout - */ - private void addRules(FormItemContainer formLayout) { + private void updateUI() { + boolean blockedForLearner = coachExclusive.isAtLeastSelected(1); + dateSwitch.setEnabled(!blockedForLearner); + groupSwitch.setEnabled(!blockedForLearner); - // disable date choosers if date switch is set to no - // enable it otherwise. - final Set<FormItem> dependenciesDateSwitch = new HashSet<FormItem>(); - dependenciesDateSwitch.add(toDate); - dependenciesDateSwitch.add(fromDate); - dependenciesDateSwitch.add(dateSubContainer); + boolean dateEnabled = dateSwitch.isAtLeastSelected(1) && dateSwitch.isEnabled(); + toDate.setVisible(dateEnabled); + fromDate.setVisible(dateEnabled); + dateSubContainer.setVisible(dateEnabled); - final Set<FormItem> dependenciesAttributeSwitch = new HashSet<FormItem>(); - // only add when initialized. is null when shibboleth module is not enabled - if (shibbolethModule.isEnableShibbolethCourseEasyConfig()) { - dependenciesAttributeSwitch.add(attributeBconnector); - } + boolean assessmentEnabled = assessmentSwitch.isAtLeastSelected(1); + assessSubContainer.setVisible(assessmentEnabled); + assessmentTypeSwitch.setVisible(assessmentEnabled); + nodePassed.setVisible(assessmentEnabled); - // show elements dependent on other values set. - FormItemDependencyRule hideClearDateSwitchDeps = RulesFactory.createCustomRule(dateSwitch, null, dependenciesDateSwitch, formLayout); - hideClearDateSwitchDeps.setDependencyRuleApplayable(new DependencyRuleApplayable() { - public void apply(FormItem triggerElement, Object triggerVal, Set<FormItem> targets) { - toDate.setDate(null); - toDate.setVisible(false); - fromDate.setDate(null); - fromDate.setVisible(false); - toDate.clearError(); - fromDate.clearError(); - dateSwitch.clearError(); - dateSubContainer.setVisible(false); - - fromDate.setFocus(false); - /* - * special rules for apply rules for coach and for assessment dependent - */ - //assessment switch only enabled if nodes to be selected - boolean coachExclIsOn = coachExclusive.getSelectedKeys().size() == 1; - assessmentSwitch.setEnabled(!coachExclIsOn && (nodeIdentList.size() > 0 || isSelectedNodeDeleted())); - - showOrHideApplyRulesForCoach(); - } - }); - RulesFactory.createShowRule(dateSwitch, "ison", dependenciesDateSwitch, formLayout); - FormItemDependencyRule toggleApplyRule = RulesFactory.createCustomRule(dateSwitch, "ison", dependenciesDateSwitch, formLayout); - toggleApplyRule.setDependencyRuleApplayable(new DependencyRuleApplayable() { - public void apply(FormItem triggerElement, Object triggerVal, Set<FormItem> targets) { - - fromDate.setFocus(true); - - //assessment switch only enabled if nodes to be selected - assessmentSwitch.setEnabled((nodeIdentList.size() > 0 || isSelectedNodeDeleted())); - - showOrHideApplyRulesForCoach(); - } - }); + boolean groupEnabled = groupSwitch.isAtLeastSelected(1) && groupSwitch.isEnabled(); + groupSubContainer.setVisible(groupEnabled); + easyGroupList.setFocus(groupEnabled); - if (shibbolethModule.isEnableShibbolethCourseEasyConfig()) { - FormItemDependencyRule hideClearAttibuteSwitchDeps = RulesFactory.createCustomRule(attributeSwitch, null, dependenciesAttributeSwitch, formLayout); - - hideClearAttibuteSwitchDeps.setDependencyRuleApplayable(new DependencyRuleApplayable() { - public void apply(FormItem triggerElement, Object triggerVal, Set<FormItem> targets) { - attributeSwitch.clearError(); - attributeBconnector.select(BCON_VAL_AND, true); - attributeBconnector.setVisible(false); - if(attribteRowAdderSubform!=null){ - attribteRowAdderSubform.cleanUp(); - } - showOrHideApplyRulesForCoach(); - } - }); - - RulesFactory.createShowRule(attributeSwitch, "ison", dependenciesAttributeSwitch, formLayout); - - FormItemDependencyRule attributeSwitchtoggleApplyRule = RulesFactory.createCustomRule(attributeSwitch, "ison", dependenciesAttributeSwitch, formLayout); - attributeSwitchtoggleApplyRule.setDependencyRuleApplayable(new DependencyRuleApplayable() { - public void apply(FormItem triggerElement, Object triggerVal, Set<FormItem> targets) { - attributeBconnector.setVisible(true); - if(attribteRowAdderSubform!=null){ - attribteRowAdderSubform.init(); - } - showOrHideApplyRulesForCoach(); - } - }); - } - - // - // enable textfields and subworkflow-start-links if groups is yes - // disable it otherwise - final Set<FormItem> dependenciesGroupSwitch = new HashSet<FormItem>(); - dependenciesGroupSwitch.add(groupSubContainer); - FormItemDependencyRule hideClearGroupSwitchDeps = RulesFactory.createCustomRule(groupSwitch, null, dependenciesGroupSwitch, formLayout); - hideClearGroupSwitchDeps.setDependencyRuleApplayable(new DependencyRuleApplayable() { - public void apply(FormItem triggerElement, Object triggerVal, Set<FormItem> targets) { - - easyAreaList.clearError(); - easyGroupList.clearError(); - groupSwitch.clearError(); - groupSubContainer.setVisible(false); - - if (shibbolethModule.isEnableShibbolethCourseEasyConfig()) { - attributeSwitch.clearError(); - } - easyGroupList.setFocus(false); - - //assessment switch only enabled if nodes to be selected - boolean coachExclIsOn = coachExclusive.getSelectedKeys().size() == 1; - assessmentSwitch.setEnabled(!coachExclIsOn && (nodeIdentList.size() > 0 || isSelectedNodeDeleted())); - - showOrHideApplyRulesForCoach(); - } - }); - RulesFactory.createShowRule(groupSwitch, "ison", dependenciesGroupSwitch, formLayout); - toggleApplyRule = RulesFactory.createCustomRule(groupSwitch, "ison", dependenciesGroupSwitch, formLayout); - toggleApplyRule.setDependencyRuleApplayable(new DependencyRuleApplayable() { - public void apply(FormItem triggerElement, Object triggerVal, Set<FormItem> targets) { - - easyGroupList.setFocus(true); - - //assessment switch only enabled if nodes to be selected - assessmentSwitch.setEnabled((nodeIdentList.size() > 0 || isSelectedNodeDeleted())); - - showOrHideApplyRulesForCoach(); - } - }); + boolean cutValueVisible = assessmentTypeSwitch.isVisible() + && NODEPASSED_VAL_SCORE.equals(assessmentTypeSwitch.getSelectedKey()); + cutValue.setVisible(cutValueVisible); - // - // dependencies of assessment switch - final Set<FormItem> assessDeps = new HashSet<FormItem>(); - assessDeps.add(assessmentTypeSwitch); - assessDeps.add(nodePassed); - assessDeps.add(cutValue); - assessDeps.add(assessSubContainer); - - // show elements dependent on other values set. - FormItemDependencyRule showAssessmentSwitchDeps = RulesFactory.createCustomRule(assessmentSwitch, "ison", assessDeps, formLayout); - showAssessmentSwitchDeps.setDependencyRuleApplayable(new DependencyRuleApplayable() { - public void apply(FormItem triggerElement, Object triggerVal, Set<FormItem> targets) { - boolean cutValueVisibility = assessmentTypeSwitch.getSelectedKey().equals(NODEPASSED_VAL_SCORE); - assessSubContainer.setVisible(true); - assessmentTypeSwitch.setVisible(true); - nodePassed.setVisible(true); - cutValue.setVisible(cutValueVisibility); - assessmentSwitch.clearError(); - cutValue.clearError(); - nodePassed.clearError(); - - showOrHideApplyRulesForCoach(); - } - }); - - // hide elements and reset values. - FormItemDependencyRule hideResetAssessmentSwitchDeps = RulesFactory.createCustomRule(assessmentSwitch, null, assessDeps, formLayout); - hideResetAssessmentSwitchDeps.setDependencyRuleApplayable(new DependencyRuleApplayable() { - public void apply(FormItem triggerElement, Object triggerVal, Set<FormItem> targets) { - assessSubContainer.setVisible(false); - assessmentTypeSwitch.select(NODEPASSED_VAL_PASSED, true); - assessmentTypeSwitch.setVisible(false); - nodePassed.select(NO_NODE_SELECTED_IDENTIFYER, true); - nodePassed.setVisible(false); - cutValue.setIntValue(0); - cutValue.setVisible(false); - - showOrHideApplyRulesForCoach(); - } - }); - - final Set<FormItem> assessTypeDeps = new HashSet<FormItem>(); - assessTypeDeps.add(cutValue); - RulesFactory.createHideRule(assessmentTypeSwitch, NODEPASSED_VAL_PASSED, assessTypeDeps, assessSubContainer); - RulesFactory.createShowRule(assessmentTypeSwitch, NODEPASSED_VAL_SCORE, assessTypeDeps, assessSubContainer); - - // - // - final Set<FormItem> dependenciesCoachExclusiveReadonly = new HashSet<FormItem>(); - dependenciesCoachExclusiveReadonly.addAll(dependenciesDateSwitch); - dependenciesCoachExclusiveReadonly.addAll(dependenciesGroupSwitch); - dependenciesCoachExclusiveReadonly.addAll(assessDeps); - dependenciesCoachExclusiveReadonly.addAll(dependenciesAttributeSwitch); - - // coach exclusive switch rules - // -> custom rule implementation because it is not a simple hide / show rule - // while disabling reset the elements - FormItemDependencyRule disableAndResetOthers = RulesFactory.createCustomRule(coachExclusive, "ison", - dependenciesCoachExclusiveReadonly, formLayout); - disableAndResetOthers.setDependencyRuleApplayable(new DependencyRuleApplayable() { - public void apply(FormItem triggerElement, Object triggerVal, Set<FormItem> targets) { - // disable and remove checkbox selection - // uncheck and disable checkboxes - dateSwitch.select("ison", false); - groupSwitch.select("ison", false); - assessmentSwitch.select("ison", false); - dateSwitch.setEnabled(false); - toDate.setDate(null); - fromDate.setDate(null); - groupSwitch.setEnabled(false); - easyAreaList.setValue(""); - easyAreaList.setUserObject(new ArrayList<Long>()); - easyGroupList.setValue(""); - easyGroupList.setUserObject(new ArrayList<Long>()); - assessmentSwitch.setEnabled(false); - assessmentMode.select("ison", false); - assessmentMode.setEnabled(false); - - // disable the shibboleth attributes switch and reset the row subform - if (attributeSwitch != null) { - attributeSwitch.select("ison", false); - attributeSwitch.setEnabled(false); + //assessment switch only enabled if nodes to be selected + assessmentSwitch.setEnabled(!blockedForLearner && (!nodeIdentList.isEmpty() || isSelectedNodeDeleted())); + assessmentMode.setEnabled(!blockedForLearner); + + //default is a checked disabled apply rules for coach + if (attributeSwitch != null) { + attributeSwitch.setEnabled(!blockedForLearner); + + boolean attributeEnabled = attributeSwitch.isAtLeastSelected(1) && attributeSwitch.isEnabled(); + attributeBconnector.setVisible(attributeEnabled); + if(attribteRowAdderSubform != null) { + if(attributeEnabled) { + attribteRowAdderSubform.init(); + } else { attribteRowAdderSubform.cleanUp(); - attributeSwitch.clearError(); - } - showOrHideApplyRulesForCoach(); - - // hide (e.g. remove) general erros - dateSwitch.clearError(); - groupSwitch.clearError(); - assessmentSwitch.clearError(); - - - // all dependent elements become invisible - for (Iterator<FormItem> iter = dependenciesCoachExclusiveReadonly.iterator(); iter.hasNext();) { - FormItem element = iter.next(); - element.setVisible(false); } } - }); - - // two rules to bring them back visible and also checkable - // dependencies of assessment switch - final Set<FormItem> switchesOnly = new HashSet<FormItem>(); - switchesOnly.add(dateSwitch); - switchesOnly.add(groupSwitch); - switchesOnly.add(assessmentSwitch); - switchesOnly.add(applyRulesForCoach); - if (shibbolethModule.isEnableShibbolethCourseEasyConfig()) { - switchesOnly.add(attributeSwitch); } - - FormItemDependencyRule enableOthers = RulesFactory.createCustomRule(coachExclusive, null, switchesOnly, formLayout); - enableOthers.setDependencyRuleApplayable(new DependencyRuleApplayable() { - private boolean firedDuringInit = true; - public void apply(FormItem triggerElement, Object triggerVal, Set<FormItem> targets) { - dateSwitch.setEnabled(true); - groupSwitch.setEnabled(true); - //assessment switch only enabled if nodes to be selected - assessmentSwitch.setEnabled((nodeIdentList.size() > 0 || isSelectedNodeDeleted())); - assessmentMode.setEnabled(true); - - //default is a checked disabled apply rules for coach - if (shibbolethModule.isEnableShibbolethCourseEasyConfig()) { - attributeSwitch.setEnabled(true); - } - if(!firedDuringInit){ - showOrHideApplyRulesForCoach(); - } - firedDuringInit = false; - } - }); - - // - // dependencies of assessment mode - final Set<FormItem> assessModeDeps = new HashSet<FormItem>(); - - // show elements dependent on other values set. - FormItemDependencyRule showAssessmentModeDeps = RulesFactory.createCustomRule(assessmentMode, "ison", assessModeDeps, formLayout); - showAssessmentModeDeps.setDependencyRuleApplayable(new DependencyRuleApplayable() { - public void apply(FormItem triggerElement, Object triggerVal, Set<FormItem> targets) { - showOrHideApplyRulesForCoach(); - } - }); - - // hide elements and reset values. - FormItemDependencyRule hideResetAssessmentModeDeps = RulesFactory.createCustomRule(assessmentMode, null, assessModeDeps, formLayout); - hideResetAssessmentModeDeps.setDependencyRuleApplayable(new DependencyRuleApplayable() { - public void apply(FormItem triggerElement, Object triggerVal, Set<FormItem> targets) { - showOrHideApplyRulesForCoach(); - } - }); - } - - /** - * Methods to add elements - * @param formLayout - * @param listener - */ - private void addCoachExclusive(FormItemContainer formLayout) { - /* - * yes / no chooser defines if learner do not see the building block at all - */ - coachExclusive = uifactory.addCheckboxesHorizontal("coachExclusive", null, formLayout, new String[] { "ison" }, new String[] { translate("form.easy.coachExclusive") }); - coachExclusive.setElementCssClass("o_sel_condition_coach_exclusive"); - boolean coachesAndAdminsInitValue = validatedCondition.isEasyModeCoachesAndAdmins(); - coachExclusive.select("ison", coachesAndAdminsInitValue); - // register for on click event to hide/disable other elements - coachExclusive.addActionListener(FormEvent.ONCLICK); - // rules are later added + // base on dates and so on + boolean applyRulesForCoachVisible = isDateGroupAssessmentOrAttributeSwitchOnOrAssessmentModeOn(); + applyRulesForCoach.setVisible(applyRulesForCoachVisible); } - - private void addAssessmentMode(FormItemContainer formLayout) { - assessmentMode = uifactory.addCheckboxesHorizontal("assessmentMode", null, formLayout, new String[] { "ison" }, new String[] { translate("form.easy.assessmentMode") }); - assessmentMode.select("ison", validatedCondition.isAssessmentMode()); - assessmentMode.addActionListener(FormEvent.ONCLICK); - assessmentMode.setVisible(assessmentModule.isAssessmentModeEnabled()); + + private void disableDates() { + toDate.setDate(null); + fromDate.setDate(null); + toDate.clearError(); + fromDate.clearError(); + dateSwitch.clearError(); } - - /** - * @param formLayout - * @param listener - */ - private void addApplyRulesForTutorsToo(FormItemContainer formLayout) { - - /* - * yes / no chooser defines if learner do not see the building block at all - */ - applyRulesForCoach = uifactory.addCheckboxesHorizontal("applyRulesForCoach", null, formLayout, new String[] { "ison" }, new String[] { translate("form.easy.applyRulesForCoach") }); - if(isDateGroupAssessmentOrAttributeSwitchOnOrAssessmentModeOn()) { - applyRulesForCoach.setVisible(true); - } else { - applyRulesForCoach.setVisible(false); - } - //note that in the condition this rule is saved with the opposite meaning: - // true when - // coach and admins always have access, false when rule should apply also to - // them - boolean alwaysAllowCoachesAndAdminsInitValue = validatedCondition.isEasyModeAlwaysAllowCoachesAndAdmins(); - if (alwaysAllowCoachesAndAdminsInitValue) { - applyRulesForCoach.select("ison", false); - } else { - applyRulesForCoach.select("ison", true); - } + + private void disableAssessment() { + assessmentTypeSwitch.select(NODEPASSED_VAL_PASSED, true); + nodePassed.select(NO_NODE_SELECTED_IDENTIFYER, true); + cutValue.setIntValue(0); } - - /** - * @param formLayout - * @param listener - */ - private void addFromToDateChooser(FormItemContainer formLayout) { - /* - * yes / no switch if a date.time constraint is defined - */ - dateSubContainer = FormLayoutContainer.createDefaultFormLayout("dateSubContainer", getTranslator()); - formLayout.add(dateSubContainer); - - fromDate = new JSDateChooser("fromDate", getLocale()); - fromDate.setLabel("form.easy.bdate", null); - fromDate.setDate(ConditionDateFormatter.parse(validatedCondition.getEasyModeBeginDate())); - fromDate.setExampleKey("form.easy.example.bdate", null); - fromDate.setDateChooserTimeEnabled(true); - fromDate.setDisplaySize(fromDate.getExampleDateString().length()); - dateSubContainer.add(fromDate); - - toDate = new JSDateChooser("toDate", getLocale()); - toDate.setLabel("form.easy.edate", null); - toDate.setDate(ConditionDateFormatter.parse(validatedCondition.getEasyModeEndDate())); - toDate.setExampleKey("form.easy.example.edate", null); - toDate.setDateChooserTimeEnabled(true); - toDate.setDisplaySize(toDate.getExampleDateString().length()); - dateSubContainer.add(toDate); - - dateSwitch = uifactory.addCheckboxesHorizontal("dateSwitch", null, formLayout, new String[] { "ison" }, new String[] { translate("form.easy.dateSwitch") }); - if (fromDate.getDate() != null || toDate.getDate() != null) { - dateSwitch.select("ison", true); - } else { - dateSwitch.select("ison", false); + + private void disableAttribute() { + attributeSwitch.clearError(); + attributeBconnector.select(BCON_VAL_AND, true); + if(attribteRowAdderSubform != null) { + attribteRowAdderSubform.cleanUp(); } - dateSwitch.addActionListener(FormEvent.ONCLICK); } - - /** - * @param formLayout - * @param listener - */ - private void addEasyGroupAreaChoosers(FormItemContainer formLayout) { - - groupSubContainer = FormLayoutContainer.createBareBoneFormLayout("groupSubContainer", getTranslator()); - formLayout.add(groupSubContainer); - - List<Long> groupKeyList = validatedCondition.getEasyModeGroupAccessIdList(); - String groupInitVal = getGroupNames(groupKeyList); - List<Long> areaKeyList = validatedCondition.getEasyModeGroupAreaAccessIdList(); - String areaInitVal = getAreaNames(areaKeyList); - - groupSwitch = uifactory.addCheckboxesHorizontal("groupSwitch", null, formLayout, new String[] { "ison" }, new String[] { translate("form.easy.groupSwitch") }); - groupSwitch.setElementCssClass("o_sel_condition_groups"); - // initialize selection - if (!groupKeyList.isEmpty() || !areaKeyList.isEmpty()) { - groupSwitch.select("ison", true); - } else { - groupSwitch.select("ison", false); + + private void disableGroup() { + easyAreaList.clearError(); + easyGroupList.clearError(); + groupSwitch.clearError(); + if (shibbolethModule.isEnableShibbolethCourseEasyConfig()) { + attributeSwitch.clearError(); } - groupSwitch.addActionListener(FormEvent.ONCLICK); - - //groups - groupChooseSubContainer = FormLayoutContainer.createDefaultFormLayout("groupChooseSubContainer", getTranslator()); - groupSubContainer.add(groupChooseSubContainer); - - easyGroupList = uifactory.addStaticTextElement("groupList", "form.easy.group", groupInitVal, groupChooseSubContainer); - easyGroupList.setUserObject(groupKeyList); - - chooseGroupsLink = uifactory.addFormLink("choose", groupChooseSubContainer, "o_form_groupchooser"); - chooseGroupsLink.setElementCssClass("o_sel_condition_choose_groups"); - createGroupsLink = uifactory.addFormLink("create", groupChooseSubContainer, "o_form_groupchooser"); - createGroupsLink.setElementCssClass("o_sel_condition_create_groups"); - - //areas - areaChooseSubContainer = FormLayoutContainer.createDefaultFormLayout("areaChooseSubContainer", getTranslator()); - groupSubContainer.add(areaChooseSubContainer); - - easyAreaList = uifactory.addStaticTextElement("groupList", "form.easy.area", areaInitVal, areaChooseSubContainer); - easyAreaList.setUserObject(areaKeyList); - - chooseAreasLink = uifactory.addFormLink("choose", areaChooseSubContainer, "o_form_groupchooser"); - createAreasLink = uifactory.addFormLink("create", areaChooseSubContainer, "o_form_groupchooser"); - - updateGroupsAndAreasCheck(); } - - private void addAssessmentSwitch(FormItemContainer formLayout) { - - assessSubContainer = FormLayoutContainer.createDefaultFormLayout("assessSubContainer", getTranslator()); - formLayout.add(assessSubContainer); - - Translator translator = getTranslator(); - - final String[] assessmentSwitchKeys = new String[] { NODEPASSED_VAL_PASSED, NODEPASSED_VAL_SCORE }; - final String[] assessmentSwitchValues = new String[] { translator.translate("form.easy.assessmentSwitch.passed"), - translator.translate("form.easy.assessmentSwitch.score") }; - - String nodePassedInitVal = validatedCondition.getEasyModeNodePassedId(); - String cutInitStrValue = validatedCondition.getEasyModeCutValue(); - int cutInitValue = 0; - - assessmentSwitch = uifactory.addCheckboxesHorizontal("assessmentSwitch", null, formLayout, new String[] { "ison" }, new String[] { translate("form.easy.assessmentSwitch") }); - assessmentSwitch.addActionListener(FormEvent.ONCLICK); - - - boolean selectedNodeIsInList = false; - List<String> keysList = new ArrayList<String>(); - List<String> valuesList = new ArrayList<String>(); - if (nodeIdentList.size() > 0) { - // there are nodes to be selected - keysList.add(NO_NODE_SELECTED_IDENTIFYER); - valuesList.add("- " + translator.translate("form.easy.nodePassed.select") + " -"); - for (int i = 0; i < nodeIdentList.size(); i++) { - CourseNode courseNode = nodeIdentList.get(i); - keysList.add(courseNode.getIdent()); - valuesList.add(courseNode.getShortName() + " (Id:" + courseNode.getIdent() + ")"); - if (courseNode.getIdent().equals(nodePassedInitVal)) selectedNodeIsInList = true; - } - } else { - // no nodes to be selected - keysList.add(NO_NODE_SELECTED_IDENTIFYER); - valuesList.add("- " + translator.translate("form.easy.nodePassed.noNodes")); - //disable switch - assessmentSwitch.setEnabled(false); - } - // add dummy value if needed - if (nodePassedInitVal != null && !selectedNodeIsInList) { - keysList.add(DELETED_NODE_IDENTIFYER); - valuesList.add("- " + translator.translate("form.easy.nodePassed.deletedNode") + " -"); - } - final String[] nodePassedKeys = new String[keysList.size()]; - keysList.toArray(nodePassedKeys); - final String[] nodePassedValues = new String[valuesList.size()]; - valuesList.toArray(nodePassedValues); - - nodePassed = uifactory.addDropdownSingleselect("nodePassed", "form.easy.nodePassed", assessSubContainer, nodePassedKeys, nodePassedValues, null); - if (nodePassedInitVal != null) { - if (selectedNodeIsInList) { - nodePassed.select(nodePassedInitVal, true); - } else { - nodePassed.select(DELETED_NODE_IDENTIFYER, true); - } - } else { - nodePassed.select(NO_NODE_SELECTED_IDENTIFYER, true); - } + + private void setBlockedForLearner() { + dateSwitch.uncheckAll(); + groupSwitch.uncheckAll(); + assessmentSwitch.uncheckAll(); + toDate.setDate(null); + fromDate.setDate(null); + easyAreaList.setValue(""); + easyAreaList.setUserObject(new ArrayList<Long>()); + easyGroupList.setValue(""); + easyGroupList.setUserObject(new ArrayList<Long>()); + assessmentMode.uncheckAll(); - assessmentTypeSwitch = uifactory.addRadiosVertical("assessmentTypeSwitch", null, assessSubContainer, - assessmentSwitchKeys, assessmentSwitchValues); - assessmentTypeSwitch.setLabel("form.easy.assessmentSwitch.type", null); - assessmentTypeSwitch.addActionListener(FormEvent.ONCLICK); - - if (nodePassedInitVal != null) { - // has a node configured - if (cutInitStrValue == null) { - // with cut value - assessmentTypeSwitch.select(NODEPASSED_VAL_PASSED, true); - } else { - cutInitValue = Integer.valueOf(cutInitStrValue); - assessmentTypeSwitch.select(NODEPASSED_VAL_SCORE, true); - } - assessmentSwitch.select("ison", true); - assessmentTypeSwitch.setVisible(true); - } else { - assessmentSwitch.select("ison", false); - assessmentTypeSwitch.setVisible(false); - assessmentTypeSwitch.select(NODEPASSED_VAL_PASSED, true); + // disable the shibboleth attributes switch and reset the row subform + if (attributeSwitch != null) { + attributeSwitch.uncheckAll(); + attributeSwitch.clearError(); + attribteRowAdderSubform.cleanUp(); } - - cutValue = uifactory.addIntegerElement("cutval", "form.easy.cutValue", cutInitValue, assessSubContainer); - cutValue.setDisplaySize(3); } + /* * HELPER METHODS AFTER HERE */ @@ -1354,6 +983,148 @@ public class ConditionConfigEasyController extends FormBasicController implement chooseAreasLink.setVisible(!createAreasLink.isVisible()); } + + private void doChooseGroup(UserRequest ureq) { + removeAsListenerAndDispose(cmc); + removeAsListenerAndDispose(groupChooseC); + + List<Long> groupKeys = getKeys(easyGroupList); + groupChooseC = new GroupSelectionController(ureq, getWindowControl(), true, + courseEditorEnv.getCourseGroupManager(), groupKeys); + listenTo(groupChooseC); + + cmc = new CloseableModalController(getWindowControl(), "close", groupChooseC.getInitialComponent(), + true, getTranslator().translate("popupchoosegroups")); + listenTo(cmc); + cmc.activate(); + } + + private void doGroupChoosed(UserRequest ureq, List<Long> groupKeys) { + easyGroupList.setUserObject(groupKeys); + easyGroupList.setValue(getGroupNames(groupKeys)); + validateGroupFields(); + easyGroupList.getRootForm().submit(ureq); + } + + private void doCreateGroup(UserRequest ureq) { + removeAsListenerAndDispose(cmc); + removeAsListenerAndDispose(groupCreateCtlr); + + OLATResource courseResource = courseEditorEnv.getCourseGroupManager().getCourseResource(); + RepositoryEntry courseRe = RepositoryManager.getInstance().lookupRepositoryEntry(courseResource, false); + groupCreateCtlr = new NewBGController(ureq, getWindowControl(), courseRe, true, null); + listenTo(groupCreateCtlr); + cmc = new CloseableModalController(getWindowControl(), "close", groupCreateCtlr.getInitialComponent()); + listenTo(cmc); + cmc.activate(); + } + + private void doGroupCreated(UserRequest ureq, Collection<Long> groupKeys) { + List<Long> c = new ArrayList<>(); + c.addAll(getKeys(easyGroupList)); + if (fixGroupError != null && fixGroupError.getUserObject() != null) { + c.removeAll(Arrays.asList((String[])fixGroupError.getUserObject())); + } + c.addAll(groupKeys); + easyGroupList.setValue(getGroupNames(c)); + easyGroupList.setUserObject(c); + easyGroupList.getRootForm().submit(ureq); + validateGroupFields(); + + if (!groupKeys.isEmpty()) { + singleUserEventCenter.fireEventToListenersOf(new MultiUserEvent("changed"), groupConfigChangeEventOres); + } + } + + /** + * user wants to fix problem with fixing group error link e.g. create on + * or more group at once. + * @param ureq + */ + private void doFixGroupError(UserRequest ureq) { + String[] csvGroupName = (String[]) fixGroupError.getUserObject(); + OLATResource courseResource = courseEditorEnv.getCourseGroupManager().getCourseResource(); + RepositoryEntry courseRe = RepositoryManager.getInstance().lookupRepositoryEntry(courseResource, false); + removeAsListenerAndDispose(groupCreateCtlr); + groupCreateCtlr = new NewBGController(ureq, getWindowControl(), courseRe, true, csvGroupName[0]); + listenTo(groupCreateCtlr); + + removeAsListenerAndDispose(cmc); + cmc = new CloseableModalController(getWindowControl(), "close", groupCreateCtlr.getInitialComponent()); + listenTo(cmc); + cmc.activate(); + } + + private void doChooseArea(UserRequest ureq) { + removeAsListenerAndDispose(cmc); + removeAsListenerAndDispose(areaChooseC); + + areaChooseC = new AreaSelectionController(ureq, getWindowControl(), true, + courseEditorEnv.getCourseGroupManager(), getKeys(easyAreaList)); + listenTo(areaChooseC); + + cmc = new CloseableModalController(getWindowControl(), "close", areaChooseC.getInitialComponent(), + true, translate("popupchooseareas")); + listenTo(cmc); + cmc.activate(); + } + + private void doAreaChoosed(UserRequest ureq, List<Long> areaKeys) { + easyAreaList.setUserObject(areaKeys); + easyAreaList.setValue(this.getAreaNames(areaKeys)); + validateGroupFields(); + easyAreaList.getRootForm().submit(ureq); + } + + private void doCreateArea(UserRequest ureq) { + removeAsListenerAndDispose(cmc); + removeAsListenerAndDispose(areaCreateCtlr); + + OLATResource courseResource = courseEditorEnv.getCourseGroupManager().getCourseResource(); + areaCreateCtlr = new NewAreaController(ureq, getWindowControl(), courseResource, true, null); + listenTo(areaCreateCtlr); + + cmc = new CloseableModalController(getWindowControl(), "close", areaCreateCtlr.getInitialComponent()); + listenTo(cmc); + cmc.activate(); + } + + private void doAreaCreated(UserRequest ureq, Collection<Long> createdAreaKeys) { + List<Long> c = new ArrayList<>(); + c.addAll(getKeys(easyAreaList)); + if (fixAreaError!= null && fixAreaError.getUserObject() != null) { + c.removeAll(Arrays.asList((String[])fixAreaError.getUserObject())); + } + c.addAll(createdAreaKeys); + + easyAreaList.setValue(getAreaNames(c)); + easyAreaList.setUserObject(c); + easyAreaList.getRootForm().submit(ureq); + validateGroupFields(); + + if (!createdAreaKeys.isEmpty()) { + singleUserEventCenter.fireEventToListenersOf(new MultiUserEvent("changed"), groupConfigChangeEventOres); + } + } + + /** + * User wants to fix problem with fixing area error link e.g. create one + * or more areas at once. + * + * @param The user request + */ + private void doFixArea(UserRequest ureq) { + String[] csvAreaName = (String[]) fixAreaError.getUserObject(); + OLATResource courseResource = courseEditorEnv.getCourseGroupManager().getCourseResource(); + removeAsListenerAndDispose(areaCreateCtlr); + areaCreateCtlr = new NewAreaController(ureq, getWindowControl(), courseResource, true, csvAreaName[0]); + listenTo(areaCreateCtlr); + + removeAsListenerAndDispose(cmc); + cmc = new CloseableModalController(getWindowControl(), "close", areaCreateCtlr.getInitialComponent()); + listenTo(cmc); + cmc.activate(); + } /** * It checks if the selected EasyModeNodePassedId is not null, while the assessable node list is empty, @@ -1363,7 +1134,7 @@ public class ConditionConfigEasyController extends FormBasicController implement */ private boolean isSelectedNodeDeleted() { String nodePassedInitVal = validatedCondition.getEasyModeNodePassedId(); - if(nodePassedInitVal!=null && nodeIdentList.size()==0) { + if(nodePassedInitVal!=null && nodeIdentList.isEmpty()) { assessmentSwitch.setEnabled(true); return true; @@ -1372,18 +1143,14 @@ public class ConditionConfigEasyController extends FormBasicController implement } private boolean isEmpty(StaticTextElement element) { - List<Long> keys = getKeys(element); - if(keys == null || keys.isEmpty()) { - return true; - } - return false; + return getKeys(element).isEmpty(); } private List<Long> getKeys(StaticTextElement element) { @SuppressWarnings("unchecked") List<Long> keys = (List<Long>)element.getUserObject(); if(keys == null) { - keys = new ArrayList<Long>(); + keys = new ArrayList<>(); element.setUserObject(keys); } return keys; diff --git a/src/main/java/org/olat/course/condition/_content/easycondedit.html b/src/main/java/org/olat/course/condition/_content/easycondedit.html index f557e974f0c..50737c88cb4 100644 --- a/src/main/java/org/olat/course/condition/_content/easycondedit.html +++ b/src/main/java/org/olat/course/condition/_content/easycondedit.html @@ -2,37 +2,36 @@ ## block this node from learner $r.render("coachExclusive") ## date switch, from and to date - <!-- dateswitch --> - <!-- generates --> - <!-- Date dependent?:| | [.] | | from | |[.....][chooser] | - | | | | to | |[.....][chooser] |--> +## dateswitch --> +## Date dependent?:| | [.] | | from | |[.....][chooser] | +## | | | | to | |[.....][chooser] | $r.render("dateSwitch") #if ($f.isVisible("dateSubContainer")) $r.render("dateSubContainer") <div class="col-sm-9 col-sm-offset-3">$r.render("dateSubContainer_ERROR")</div> #end + ## group switch, group and group area listing - <!-- groupswitch --> - <!-- generates --> - <!-- Group dependent?:| | [.] | | Groups | |[.....][chooser] | - | | | | Areas | |[.....][chooser] | --> +## groupswitch --> +## Group dependent?:| | [.] | | Groups | |[.....][chooser] | +## | | | | Areas | |[.....][chooser] | $r.render("groupSwitch") #if ($f.isVisible("groupSubContainer")) $r.render("groupSubContainer") <div class="col-sm-9 col-sm-offset-3">$r.render("groupSubContainer_ERROR")</div> #end + ## assessment switch, cutvalue or score switch and score value - <!-- assessswitch --> - <!-- generates --> - <!-- Assess dependent?:| |[.] | | | O PASSED | | - | | | | | X SCORE | | - | | | | Kursbaustein | [.....V] | | - | | | | Cut value | [...] | |--> +## assessswitch +## Assess dependent?:| |[.] | | | O PASSED | | +## | | | | | X SCORE | | +## | | | | Kursbaustein | [.....V] | | +## | | | | Cut value | [...] | | $r.render("assessmentSwitch") #if ($f.isVisible("assessSubContainer")) $r.render("assessSubContainer") - #end - + #end + ## attribute switch, shibboleth attribute choosers #if ($shibbolethEnabled) $r.render("attributeSwitch") @@ -41,13 +40,11 @@ $r.render("attributeBconnector") $r.render("attribteRowAdderSubform") </div> - #end + #end #end -## apply rules also for coach - $r.render("applyRulesForCoach") $r.render("assessmentMode") -## submit button + $r.render("applyRulesForCoach") <div class="o_button_group"> $r.render("subm") </div> diff --git a/src/main/java/org/olat/course/nodes/scorm/ScormEditController.java b/src/main/java/org/olat/course/nodes/scorm/ScormEditController.java index de461d53dc1..9a846d89d73 100644 --- a/src/main/java/org/olat/course/nodes/scorm/ScormEditController.java +++ b/src/main/java/org/olat/course/nodes/scorm/ScormEditController.java @@ -29,6 +29,7 @@ import java.io.File; import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.Component; +import org.olat.core.gui.components.form.flexible.FormItem; import org.olat.core.gui.components.form.flexible.FormItemContainer; import org.olat.core.gui.components.form.flexible.elements.IntegerElement; import org.olat.core.gui.components.form.flexible.elements.MultipleSelectionElement; @@ -36,7 +37,6 @@ import org.olat.core.gui.components.form.flexible.elements.SelectionElement; import org.olat.core.gui.components.form.flexible.elements.SingleSelection; import org.olat.core.gui.components.form.flexible.impl.FormBasicController; import org.olat.core.gui.components.form.flexible.impl.FormEvent; -import org.olat.core.gui.components.form.flexible.impl.rules.RulesFactory; import org.olat.core.gui.components.link.Link; import org.olat.core.gui.components.link.LinkFactory; import org.olat.core.gui.components.panel.Panel; @@ -99,8 +99,8 @@ public class ScormEditController extends ActivateableTabbableDefaultController i public static final String CONFIG_CUTVALUE = "cutvalue"; public static final String CONFIG_DELIVERY_OPTIONS = "deliveryOptions"; - public final static String CONFIG_FULLWINDOW = "fullwindow"; - public final static String CONFIG_CLOSE_ON_FINISH = "CLOSEONFINISH"; + public static final String CONFIG_FULLWINDOW = "fullwindow"; + public static final String CONFIG_CLOSE_ON_FINISH = "CLOSEONFINISH"; // <OLATCE-289> public static final String CONFIG_MAXATTEMPTS = "attempts"; @@ -371,9 +371,7 @@ public class ScormEditController extends ActivateableTabbableDefaultController i String repoSoftkey = (String) config.get(ScormEditController.CONFIG_KEY_REPOSITORY_SOFTKEY); if (repoSoftkey == null) throw new AssertException("invalid config when being asked for references"); RepositoryManager rm = RepositoryManager.getInstance(); - RepositoryEntry entry = rm.lookupRepositoryEntryBySoftkey(repoSoftkey, strict); - // entry can be null only if !strict - return entry; + return rm.lookupRepositoryEntryBySoftkey(repoSoftkey, strict); } /** @@ -424,9 +422,12 @@ class VarForm extends FormBasicController { private SelectionElement showNavButtonsEl; private SelectionElement fullWindowEl; private SelectionElement closeOnFinishEl; - private SelectionElement isAssessableEl; + private SingleSelection isAssessableEl; private SelectionElement skipLaunchPageEl; private IntegerElement cutValueEl; + private SingleSelection attemptsEl; + private MultipleSelectionElement advanceScoreEl; + private MultipleSelectionElement scoreAttemptsEl; private boolean showMenu, showNavButtons, skipLaunchPage; private String assessableType; @@ -434,16 +435,10 @@ class VarForm extends FormBasicController { private boolean fullWindow; private boolean closeOnFinish; private String[] assessableKeys, assessableValues; - - // <OLATCE-289> - private SingleSelection attemptsEl; - private MultipleSelectionElement advanceScoreEl; - private MultipleSelectionElement scoreAttemptsEl; private boolean advanceScore; private boolean scoreAttempts; private int maxattempts; - // </OLATCE-289> /** * @@ -451,10 +446,7 @@ class VarForm extends FormBasicController { */ public VarForm(UserRequest ureq, WindowControl wControl, boolean showMenu, boolean skipLaunchPage, boolean showNavButtons, String assessableType, int cutValue, boolean fullWindow, boolean closeOnFinish, - // <OLATCE-289> - int maxattempts, boolean advanceScore, boolean attemptsDependOnScore - // </OLATCE-289> - ) { + int maxattempts, boolean advanceScore, boolean attemptsDependOnScore) { super(ureq, wControl); this.showMenu = showMenu; this.skipLaunchPage = skipLaunchPage; @@ -463,21 +455,20 @@ class VarForm extends FormBasicController { this.cutValue = cutValue; this.fullWindow = fullWindow; this.closeOnFinish = closeOnFinish; - - // <OLATCE-289> + this.advanceScore = advanceScore; this.scoreAttempts = attemptsDependOnScore; this.maxattempts = maxattempts; - // </OLATCE-289> - assessableKeys = new String[]{ "off", ScormEditController.CONFIG_ASSESSABLE_TYPE_SCORE, - ScormEditController.CONFIG_ASSESSABLE_TYPE_PASSED }; - assessableValues = new String[]{ + assessableKeys = new String[]{ + "off", ScormEditController.CONFIG_ASSESSABLE_TYPE_SCORE, ScormEditController.CONFIG_ASSESSABLE_TYPE_PASSED + }; + assessableValues = new String[] { translate("assessable.type.none"), translate("assessable.type.score"), translate("assessable.type.passed") - }; + }; initForm (ureq); + updateUI(); } - /** * @return @@ -526,6 +517,14 @@ class VarForm extends FormBasicController { fireEvent (ureq, Event.DONE_EVENT); } + @Override + protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) { + if(isAssessableEl == source || advanceScoreEl == source) { + updateUI(); + } + super.formInnerEvent(ureq, source, event); + } + @Override protected boolean validateFormLogic(UserRequest ureq) { boolean allOk = true; @@ -562,6 +561,7 @@ class VarForm extends FormBasicController { closeOnFinishEl.select("closeonfinish", closeOnFinish); isAssessableEl = uifactory.addRadiosVertical("isassessable", "assessable.label", formLayout, assessableKeys, assessableValues); + isAssessableEl.addActionListener(FormEvent.ONCHANGE); if(ScormEditController.CONFIG_ASSESSABLE_TYPE_SCORE.equals(assessableType)) { isAssessableEl.select(assessableKeys[1], true); } else if(ScormEditController.CONFIG_ASSESSABLE_TYPE_PASSED.equals(assessableType)) { @@ -573,31 +573,14 @@ class VarForm extends FormBasicController { cutValueEl = uifactory.addIntegerElement("cutvalue", "cutvalue.label", 0, formLayout); cutValueEl.setIntValue(cutValue); cutValueEl.setDisplaySize(3); - - // <OLATCE-289> - isAssessableEl.addActionListener(FormEvent.ONCHANGE); - advanceScoreEl = uifactory.addCheckboxesHorizontal("advanceScore", "advance.score.label", formLayout, new String[]{"ison"}, new String[]{null}); + + advanceScoreEl = uifactory.addCheckboxesHorizontal("advanceScore", "advance.score.label", formLayout, new String[]{ "ison" }, new String[]{ "" }); advanceScoreEl.select("ison", advanceScore); advanceScoreEl.addActionListener(FormEvent.ONCHANGE); - //assessable type score/passed -> show "Prevent subsequent attempts from decreasing score" - RulesFactory.createHideRule(isAssessableEl, assessableKeys[0], advanceScoreEl, formLayout); - RulesFactory.createShowRule(isAssessableEl, assessableKeys[1], advanceScoreEl, formLayout); - RulesFactory.createShowRule(isAssessableEl, assessableKeys[2], advanceScoreEl, formLayout); - - //assessable type score or none -> show "Score needed to pass" - RulesFactory.createShowRule(isAssessableEl, assessableKeys[0], cutValueEl, formLayout); - RulesFactory.createShowRule(isAssessableEl, assessableKeys[1], cutValueEl, formLayout); - RulesFactory.createHideRule(isAssessableEl, assessableKeys[2], cutValueEl, formLayout); - scoreAttemptsEl = uifactory.addCheckboxesHorizontal("scoreAttempts", "attempts.depends.label", formLayout, new String[]{"ison"}, new String[]{null}); scoreAttemptsEl.select("ison", scoreAttempts); - scoreAttemptsEl.addActionListener(FormEvent.ONCHANGE); - - RulesFactory.createShowRule(advanceScoreEl, "ison", scoreAttemptsEl, formLayout); - RulesFactory.createHideRule(advanceScoreEl, null, scoreAttemptsEl, formLayout); - - // <BPS-252> BPS-252_1 + int maxNumber = 21; String[] attemptsKeys = new String[maxNumber]; attemptsKeys[0] = "0"; // position 0 means no restriction @@ -615,15 +598,23 @@ class VarForm extends FormBasicController { attemptsEl = uifactory.addDropdownSingleselect("attempts.label", formLayout, attemptsKeys, attemptsValues, null); attemptsEl.select("" + maxattempts, true); - // </OLATCE-289> uifactory.addFormSubmitButton("save", formLayout); } - // <OLATCE-289> + private void updateUI() { + String isAssessable = isAssessableEl.isOneSelected() ? isAssessableEl.getSelectedKey() : null; + //assessable type score/passed -> show "Prevent subsequent attempts from decreasing score" + advanceScoreEl.setVisible(assessableKeys[1].equals(isAssessable) || assessableKeys[2].equals(isAssessable)); + advanceScoreEl.getComponent().setDirty(true); + //assessable type score or none -> show "Score needed to pass" + cutValueEl.setVisible(assessableKeys[0].equals(isAssessable) || assessableKeys[1].equals(isAssessable)); + } + public int getAttemptsValue() { return Integer.valueOf(attemptsEl.getSelectedKey()); } + public boolean isAdvanceScore() { return advanceScoreEl.isSelected(0); } diff --git a/src/main/java/org/olat/course/nodes/st/STCourseNodeDisplayConfigFormController.java b/src/main/java/org/olat/course/nodes/st/STCourseNodeDisplayConfigFormController.java index c25a25b8ac5..e5aea5b08b9 100644 --- a/src/main/java/org/olat/course/nodes/st/STCourseNodeDisplayConfigFormController.java +++ b/src/main/java/org/olat/course/nodes/st/STCourseNodeDisplayConfigFormController.java @@ -28,7 +28,6 @@ import org.olat.core.gui.components.form.flexible.elements.SingleSelection; import org.olat.core.gui.components.form.flexible.elements.SpacerElement; import org.olat.core.gui.components.form.flexible.impl.FormBasicController; import org.olat.core.gui.components.form.flexible.impl.FormEvent; -import org.olat.core.gui.components.form.flexible.impl.rules.RulesFactory; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.Event; import org.olat.core.gui.control.WindowControl; @@ -58,18 +57,21 @@ import org.olat.modules.ModuleConfiguration; * @author gnaegi, gnaegi@frentix.com, www.frentix.com */ public class STCourseNodeDisplayConfigFormController extends FormBasicController { - private static final String[] keys_displayType = new String[] { "system", "peekview", "file", "delegate" }; + private static final String[] displayTypeKeys = new String[] { "system", "peekview", "file", "delegate" }; - // read current configuration - private String displayConfig = null; - private int columnsConfig = 1; + private SpacerElement spacerCols; private SingleSelection displayTypeRadios; private MultipleSelectionElement displayTwoColumns; private MultipleSelectionElement selectedPeekviewChildren; + private String[] selectedPeekviewChildKeys; private String[] selectedPeekviewChildValues; private String[] selectedPeekviewChildCssClasses; - private String selectedPeekviewChildNodesConfig = null; + + // read current configuration + private int columnsConfig = 1; + private String displayConfig; + private String selectedPeekviewChildNodesConfig; /** * Constructor for the config form @@ -82,9 +84,9 @@ public class STCourseNodeDisplayConfigFormController extends FormBasicController STCourseNodeDisplayConfigFormController(UserRequest ureq, WindowControl wControl, ModuleConfiguration config, CourseEditorTreeNode node) { super(ureq, wControl); // Read current configuration - this.displayConfig = config.getStringValue(STCourseNodeEditController.CONFIG_KEY_DISPLAY_TYPE, + displayConfig = config.getStringValue(STCourseNodeEditController.CONFIG_KEY_DISPLAY_TYPE, STCourseNodeEditController.CONFIG_VALUE_DISPLAY_TOC); - this.columnsConfig = config.getIntegerSafe(STCourseNodeEditController.CONFIG_KEY_COLUMNS, 1); + columnsConfig = config.getIntegerSafe(STCourseNodeEditController.CONFIG_KEY_COLUMNS, 1); // Build data model for the selected child peekview checkboxes int childCount = node.getChildCount(); selectedPeekviewChildKeys = new String[childCount]; @@ -99,6 +101,7 @@ public class STCourseNodeDisplayConfigFormController extends FormBasicController selectedPeekviewChildNodesConfig = config.getStringValue(STCourseNodeEditController.CONFIG_KEY_PEEKVIEW_CHILD_NODES, ""); // initialize the form now initForm(ureq); + updateUI(); } /** @@ -128,9 +131,9 @@ public class STCourseNodeDisplayConfigFormController extends FormBasicController setFormContextHelp("Knowledge Transfer#_struktur"); FormUIFactory formFact = FormUIFactory.getInstance(); // Display type - String[] values_displayType = new String[] { translate("form.system"), translate("form.peekview"), translate("form.self"), + String[] displayTypeValues = new String[] { translate("form.system"), translate("form.peekview"), translate("form.self"), translate("form.delegate") }; - displayTypeRadios = formFact.addRadiosVertical("selforsystemoverview", formLayout, keys_displayType, values_displayType); + displayTypeRadios = formFact.addRadiosVertical("selforsystemoverview", formLayout, displayTypeKeys, displayTypeValues); displayTypeRadios.addActionListener(FormEvent.ONCLICK); if (displayConfig.equals(STCourseNodeEditController.CONFIG_VALUE_DISPLAY_FILE)) { displayTypeRadios.select("file", true); @@ -144,49 +147,35 @@ public class STCourseNodeDisplayConfigFormController extends FormBasicController // Peekview details configuration - allow only MAX_PEEKVIEW_CHILD_NODES // peekviews to be selected if (selectedPeekviewChildKeys.length > 0) { - SpacerElement spacerChild = formFact.addSpacerElement("spacerChild", formLayout, true); - selectedPeekviewChildren = formFact.addCheckboxesVertical("selectedPeekviewChildren", formLayout, selectedPeekviewChildKeys, - selectedPeekviewChildValues, selectedPeekviewChildCssClasses, 1); + selectedPeekviewChildren = formFact.addCheckboxesVertical("selectedPeekviewChildren", formLayout, + selectedPeekviewChildKeys, selectedPeekviewChildValues, selectedPeekviewChildCssClasses, 1); selectedPeekviewChildren.setLabel("selectedPeekviewChildren", new String[] { STCourseNodeConfiguration.MAX_PEEKVIEW_CHILD_NODES + "" }); - // visibility rules for peekview children selection - RulesFactory.createHideRule(displayTypeRadios, "file", selectedPeekviewChildren, formLayout); - RulesFactory.createHideRule(displayTypeRadios, "system", selectedPeekviewChildren, formLayout); - RulesFactory.createShowRule(displayTypeRadios, "peekview", selectedPeekviewChildren, formLayout); - RulesFactory.createHideRule(displayTypeRadios, "delegate", selectedPeekviewChildren, formLayout); - RulesFactory.createHideRule(displayTypeRadios, "file", spacerChild, formLayout); - RulesFactory.createHideRule(displayTypeRadios, "system", spacerChild, formLayout); - RulesFactory.createShowRule(displayTypeRadios, "peekview", spacerChild, formLayout); - RulesFactory.createHideRule(displayTypeRadios, "delegate", spacerChild, formLayout); + // Pre-select the first MAX_PEEKVIEW_CHILD_NODES child nodes if none is // selected to reflect meaningfull default configuration preselectConfiguredOrMaxChildNodes(); // Add as listener for any changes selectedPeekviewChildren.addActionListener(FormEvent.ONCLICK); } - // + // Number of rows (only available in system or peekview type) - SpacerElement spacerCols = formFact.addSpacerElement("spacerCols", formLayout, true); - displayTwoColumns = formFact - .addCheckboxesHorizontal("displayTwoColumns", formLayout, new String[] { "on" }, new String[] { "" }); + spacerCols = formFact.addSpacerElement("spacerCols", formLayout, true); + displayTwoColumns = formFact.addCheckboxesHorizontal("displayTwoColumns", formLayout, new String[] { "on" }, new String[] { "" }); displayTwoColumns.setLabel("displayTwoColumns", null); displayTwoColumns.addActionListener(FormEvent.ONCLICK); - if (columnsConfig == 2) { - displayTwoColumns.selectAll(); + } + + private void updateUI() { + String selectedKey = displayTypeRadios.getSelectedKey(); + displayTwoColumns.setVisible("peekview".equals(selectedKey) || "system".equals(selectedKey)); + spacerCols.setVisible("peekview".equals(selectedKey) || "system".equals(selectedKey)); + if(selectedPeekviewChildren != null) { + selectedPeekviewChildren.setVisible("peekview".equals(selectedKey)); } - if (displayConfig.equals(STCourseNodeEditController.CONFIG_VALUE_DISPLAY_FILE) || displayConfig.equals(STCourseNodeEditController.CONFIG_VALUE_DISPLAY_DELEGATE)) { - displayTwoColumns.setVisible(false); + if (columnsConfig == 2) { + displayTwoColumns.select("on", true); } - // - // Visibility rules for display columns switch - RulesFactory.createHideRule(displayTypeRadios, "file", displayTwoColumns, formLayout); - RulesFactory.createShowRule(displayTypeRadios, "peekview", displayTwoColumns, formLayout); - RulesFactory.createShowRule(displayTypeRadios, "system", displayTwoColumns, formLayout); - RulesFactory.createHideRule(displayTypeRadios, "delegate", displayTwoColumns, formLayout); - RulesFactory.createHideRule(displayTypeRadios, "file", spacerCols, formLayout); - RulesFactory.createShowRule(displayTypeRadios, "peekview", spacerCols, formLayout); - RulesFactory.createShowRule(displayTypeRadios, "system", spacerCols, formLayout); - RulesFactory.createHideRule(displayTypeRadios, "delegate", spacerCols, formLayout); } /** @@ -197,8 +186,11 @@ public class STCourseNodeDisplayConfigFormController extends FormBasicController @Override protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) { super.formInnerEvent(ureq, source, event); - if (source == selectedPeekviewChildren) { - if (selectedPeekviewChildren.getSelectedKeys().size() == 0) { + if(displayTypeRadios == source) { + updateUI(); + preselectConfiguredOrMaxChildNodes(); + } else if (source == selectedPeekviewChildren) { + if (selectedPeekviewChildren.getSelectedKeys().isEmpty()) { // There must be at least one selected child selectedPeekviewChildren.setErrorKey("form.peekview.error.mandatory.child", null); return; // abort @@ -219,14 +211,8 @@ public class STCourseNodeDisplayConfigFormController extends FormBasicController // Enable all checkboxes selectedPeekviewChildren.setEnabled(true); } - } else { - // Fix problem of not-preselected items (OLAT-5610). The initial status - // from the initForm method gets lost by the re-evaluation of the - // selection element. Seems to be a flexi form bug, could not find other - // solution as this workaround. - preselectConfiguredOrMaxChildNodes(); } - // Submit form on each click on any radio or checkbox (OLAT-5610) + // Submit form on each click on any radio or checkbox fireEvent(ureq, Event.DONE_EVENT); } @@ -262,7 +248,7 @@ public class STCourseNodeDisplayConfigFormController extends FormBasicController // Pre-select the first MAX_PEEKVIEW_CHILD_NODES child nodes if none is // selected to reflect meaningfull default configuration. // - if (selectedPeekviewChildren.getSelectedKeys().size() == 0) { + if (selectedPeekviewChildren.getSelectedKeys().isEmpty()) { for (int i = 0; i < selectedPeekviewChildKeys.length; i++) { if (i < STCourseNodeConfiguration.MAX_PEEKVIEW_CHILD_NODES) { selectedPeekviewChildren.select(selectedPeekviewChildKeys[i], true); @@ -294,17 +280,15 @@ public class STCourseNodeDisplayConfigFormController extends FormBasicController moduleConfig.setStringValue(STCourseNodeEditController.CONFIG_KEY_DISPLAY_TYPE, STCourseNodeEditController.CONFIG_VALUE_DISPLAY_PEEKVIEW); // update selected peekview children - if (selectedPeekviewChildren == null || selectedPeekviewChildren.getSelectedKeys().size() == 0) { + if (selectedPeekviewChildren == null || selectedPeekviewChildren.getSelectedKeys().isEmpty()) { moduleConfig.remove(STCourseNodeEditController.CONFIG_KEY_PEEKVIEW_CHILD_NODES); } else { - selectedPeekviewChildNodesConfig = ""; + StringBuilder config = new StringBuilder(); for (String childKey : selectedPeekviewChildren.getSelectedKeys()) { - if (selectedPeekviewChildNodesConfig.length() != 0) { - // separate node id's with commas - selectedPeekviewChildNodesConfig += ","; - } - selectedPeekviewChildNodesConfig += childKey; + if (selectedPeekviewChildNodesConfig.length() > 0) config.append(","); + config.append(childKey); } + selectedPeekviewChildNodesConfig = config.toString(); moduleConfig.set(STCourseNodeEditController.CONFIG_KEY_PEEKVIEW_CHILD_NODES, selectedPeekviewChildNodesConfig); } } else if (STCourseNodeEditController.CONFIG_VALUE_DISPLAY_DELEGATE.equals(displayType)) { @@ -317,12 +301,10 @@ public class STCourseNodeDisplayConfigFormController extends FormBasicController // Let other config values from old config setup remain in config, maybe // used when user switches back to other config (OLAT-5610) } - // in both cases, also set the columns configuration - int cols = (displayTwoColumns.isSelected(0) ? 2 : 1); - moduleConfig.setIntValue(STCourseNodeEditController.CONFIG_KEY_COLUMNS, Integer.valueOf(cols)); - // Let other config values from old config setup remain in config, maybe - // used when user switches back to other config (OLAT-5610) } - } + // in both cases, also set the columns configuration + columnsConfig = displayTwoColumns.isAtLeastSelected(1) ? 2 : 1; + moduleConfig.setIntValue(STCourseNodeEditController.CONFIG_KEY_COLUMNS, columnsConfig); + } } diff --git a/src/main/java/org/olat/course/nodes/st/STCourseNodeEditController.java b/src/main/java/org/olat/course/nodes/st/STCourseNodeEditController.java index 13b028ef171..3fe383a4865 100644 --- a/src/main/java/org/olat/course/nodes/st/STCourseNodeEditController.java +++ b/src/main/java/org/olat/course/nodes/st/STCourseNodeEditController.java @@ -202,7 +202,7 @@ public class STCourseNodeEditController extends ActivateableTabbableDefaultContr } } - if (assessableChildren.size() == 0 && scoreCalc == null) { + if (assessableChildren.isEmpty() && scoreCalc == null) { // show only the no assessable children message, if no previous score // config exists. score.contextPut("noAssessableChildren", Boolean.TRUE); @@ -280,7 +280,7 @@ public class STCourseNodeEditController extends ActivateableTabbableDefaultContr * @see org.olat.core.gui.control.DefaultController#event(org.olat.core.gui.UserRequest, * org.olat.core.gui.control.Controller, org.olat.core.gui.control.Event) */ - + @Override public void event(UserRequest ureq, Controller source, Event event) { if (source instanceof NodeEditController) { if(combiLinkCtr != null && combiLinkCtr.isDoProposal()){ @@ -308,10 +308,10 @@ public class STCourseNodeEditController extends ActivateableTabbableDefaultContr } } else if(source == securitySettingForm){ if(event == Event.DONE_EVENT){ - boolean allowRelativeLinks = securitySettingForm.getAllowRelativeLinksConfig(); - stNode.getModuleConfiguration().set(CONFIG_KEY_ALLOW_RELATIVE_LINKS, allowRelativeLinks); + boolean relativeLinks = securitySettingForm.getAllowRelativeLinksConfig(); + stNode.getModuleConfiguration().set(CONFIG_KEY_ALLOW_RELATIVE_LINKS, relativeLinks); stNode.getModuleConfiguration().set(CONFIG_KEY_ALLOW_COACH_EDIT, securitySettingForm.getAllowCoachEditConfig()); - combiLinkCtr.setAllowEditorRelativeLinks(allowRelativeLinks); + combiLinkCtr.setAllowEditorRelativeLinks(relativeLinks); fireEvent(ureq, NodeEditController.NODECONFIG_CHANGED_EVENT); } } else if (source == nodeDisplayConfigFormController) { diff --git a/src/main/java/org/olat/gui/demo/guidemo/GuiDemoFlexiFormAdvancedController.java b/src/main/java/org/olat/gui/demo/guidemo/GuiDemoFlexiFormAdvancedController.java index e8802d655fb..efdbb4b6648 100644 --- a/src/main/java/org/olat/gui/demo/guidemo/GuiDemoFlexiFormAdvancedController.java +++ b/src/main/java/org/olat/gui/demo/guidemo/GuiDemoFlexiFormAdvancedController.java @@ -35,7 +35,6 @@ import org.olat.core.gui.components.form.flexible.elements.TextElement; import org.olat.core.gui.components.form.flexible.impl.FormBasicController; import org.olat.core.gui.components.form.flexible.impl.FormEvent; import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer; -import org.olat.core.gui.components.form.flexible.impl.rules.RulesFactory; import org.olat.core.gui.components.link.Link; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.WindowControl; @@ -59,16 +58,18 @@ public class GuiDemoFlexiFormAdvancedController extends FormBasicController { // Usually, the keys are i18n keys and the options correspond to their // translated values. To avoid unnecessary translation these dummy values are // defined right here. - private final static String[] keys = new String[] { "a", "b", "c" }; - private final static String[] options = new String[] { "A", "B", "C" }; + private static final String[] keys = new String[] { "a", "b", "c" }; + private static final String[] options = new String[] { "A", "B", "C" }; // For yes and no we'll use i18n keys and translate the values - private final static String[] yesOrNoKeys = new String[] { "advanced_form.yes", "advanced_form.no" }; + private static final String[] yesOrNoKeys = new String[] { "advanced_form.yes", "advanced_form.no" }; - private RichTextElement richTextElement, disabledRichTextElement; + private RichTextElement richTextElement; + private FormLayoutContainer subLayout; public GuiDemoFlexiFormAdvancedController(UserRequest ureq, WindowControl wControl) { super(ureq, wControl); initForm(ureq); + updateSubLayoutVisibility(); } /** @@ -101,33 +102,35 @@ public class GuiDemoFlexiFormAdvancedController extends FormBasicController { setFormContextHelp("Introduction"); // Mandatory and read-only text fields - this.addTextFields(formLayout); + addTextFields(formLayout); // More form items: Date, link and file selector - this.addDateLinkAndFileItems(formLayout); + addDateLinkAndFileItems(formLayout); // Separator with line uifactory.addSpacerElement("spacer", formLayout, false); // Single and multible selections (radio buttons and checkboxes) - this.addSelections(formLayout); + addSelections(formLayout); // Separator without line uifactory.addSpacerElement("spacernoline", formLayout, true); // Sublayout (shown if no is selected) - this.addSublayout(formLayout); + subLayout = FormLayoutContainer.createDefaultFormLayout("why_not_form", getTranslator()); + formLayout.add(subLayout); + // Add a text element + uifactory.addTextElement("why_not", "advanced_form.why_not?", 512, null, subLayout); // Here's a text area uifactory.addTextAreaElement("guidemo.form.textarea", 0, 2, null, formLayout); // Add some rich text elements richTextElement = uifactory.addRichTextElementForStringData("guidemo.form.richtext.simple", "guidemo.form.richtext.simple", "click <i>to</i> <b>edit</b>. This one has an event listener and an <b>external menu with auto hide</b>", -1, -1, false, null, null, formLayout, ureq.getUserSession(), getWindowControl()); - //richTextElement.addActionListener(FormEvent.ONCHANGE); - + uifactory.addRichTextElementForStringData("guidemo.form.richtext.simple2", null, "one <i>with</i> <b>height</b> and <span style='color:red'>no</span> event listener and an <b>internal</b> menu", 10, 40, true, null, null, formLayout, ureq.getUserSession(), getWindowControl()); - disabledRichTextElement = uifactory.addRichTextElementForStringData("guidemo.form.richtext.simple3", "guidemo.form.richtext.simple", "this <i>is</i> <b>disabled</b>", -1, -1, false, null, null, formLayout, ureq.getUserSession(), getWindowControl()); + TextElement disabledRichTextElement = uifactory.addRichTextElementForStringData("guidemo.form.richtext.simple3", "guidemo.form.richtext.simple", "this <i>is</i> <b>disabled</b>", -1, -1, false, null, null, formLayout, ureq.getUserSession(), getWindowControl()); disabledRichTextElement.setEnabled(false); // Button layout @@ -210,30 +213,11 @@ public class GuiDemoFlexiFormAdvancedController extends FormBasicController { horizontalRadioButtons.select(yesOrNoKeys[0], true); horizontalRadioButtons.addActionListener(FormEvent.ONCLICK); // Radios/Checkboxes need onclick because of IE bug OLAT-5753 } - - /** - * Adds a sublayout to the form. If the user selects no from the vertical - * radio buttons, the sublayout shows up and the user is asked to provide more - * information. - * - * @param formItemsFactory - * @param form - */ - private void addSublayout(FormItemContainer form) { - // Default Sublayout - final FormLayoutContainer subLayout = FormLayoutContainer.createDefaultFormLayout("why_not_form", getTranslator()); - // This doesn't work for some reason - // subLayout.setVisible(false); - form.add(subLayout); - - // Add a text element - uifactory.addTextElement("why_not", "advanced_form.why_not?", 512, null, subLayout); - - // Let's try some show/hide rules. If 'No' is selected, the sublayout shows - // up. Note: It's important to set the horizontal radio buttons to a default - // value. - RulesFactory.createHideRule(horizontalRadioButtons, yesOrNoKeys[0], subLayout, form); - RulesFactory.createShowRule(horizontalRadioButtons, yesOrNoKeys[1], subLayout, form); + + private void updateSubLayoutVisibility() { + boolean visible = horizontalRadioButtons.isOneSelected() + && horizontalRadioButtons.isSelected(1); + subLayout.setVisible(visible); } /** @@ -245,11 +229,13 @@ public class GuiDemoFlexiFormAdvancedController extends FormBasicController { * @param source * @param event */ + @Override protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) { - if (source == verticalRadioButtons) { + if(horizontalRadioButtons == source) { + updateSubLayoutVisibility(); + } else if (source == verticalRadioButtons) { if (event.wasTriggerdBy(FormEvent.ONCLICK)) { - int selectedIndex = verticalRadioButtons.getSelected(); - String selection = options[selectedIndex]; + String selection = verticalRadioButtons.getSelectedKey(); showInfo("advanced_form.your_selection_is", selection); } } else if (source == richTextElement) { diff --git a/src/main/java/org/olat/gui/demo/guidemo/GuiDemoFlexiFormHideUnhide.java b/src/main/java/org/olat/gui/demo/guidemo/GuiDemoFlexiFormHideUnhide.java index 000df14a040..34a21017ae0 100644 --- a/src/main/java/org/olat/gui/demo/guidemo/GuiDemoFlexiFormHideUnhide.java +++ b/src/main/java/org/olat/gui/demo/guidemo/GuiDemoFlexiFormHideUnhide.java @@ -24,9 +24,6 @@ */ package org.olat.gui.demo.guidemo; -import java.util.HashSet; -import java.util.Set; - import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.form.flexible.FormItem; import org.olat.core.gui.components.form.flexible.FormItemContainer; @@ -36,21 +33,16 @@ import org.olat.core.gui.components.form.flexible.elements.TextElement; import org.olat.core.gui.components.form.flexible.impl.FormBasicController; import org.olat.core.gui.components.form.flexible.impl.FormEvent; import org.olat.core.gui.components.form.flexible.impl.elements.FormSubmit; -import org.olat.core.gui.components.form.flexible.impl.rules.RulesFactory; import org.olat.core.gui.components.velocity.VelocityContainer; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.WindowControl; /** - * Description:<br> - * TODO: patrickb Class Description for GuiDemoFlexiFormHideUnhide - * * <P> * Initial Date: 10.09.2007 <br> * @author patrickb */ -public class GuiDemoFlexiFormHideUnhide extends FormBasicController{ - +public class GuiDemoFlexiFormHideUnhide extends FormBasicController { private TextElement firstName; private TextElement lastName; @@ -68,9 +60,9 @@ public class GuiDemoFlexiFormHideUnhide extends FormBasicController{ // if all preprocessing is done, create the form items // // example for simple preprocessing - check for NULL - if(data != null){ + if(data != null) { personData = data; - }else{ + } else { personData = new GuiDemoFlexiFormPersonData(); } // @@ -79,15 +71,12 @@ public class GuiDemoFlexiFormHideUnhide extends FormBasicController{ // // after initialisation you may need to do some stuff // but typically initForm(..) is the last call in the constructor. + updateVisibility(); } - /** - * @see org.olat.core.gui.components.form.flexible.impl.FormBasicController#doDispose(boolean) - */ @Override protected void doDispose() { - // TODO Auto-generated method stub - + // } /** @@ -113,6 +102,14 @@ public class GuiDemoFlexiFormHideUnhide extends FormBasicController{ initialPanel.pushContent(confirm); } + @Override + protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) { + if(checkbox == source) { + updateVisibility(); + } + super.formInnerEvent(ureq, source, event); + } + /** * @see org.olat.core.gui.components.form.flexible.impl.FormBasicController#initForm(org.olat.core.gui.components.form.flexible.FormItemContainer, org.olat.core.gui.control.Controller, org.olat.core.gui.UserRequest) */ @@ -143,24 +140,18 @@ public class GuiDemoFlexiFormHideUnhide extends FormBasicController{ institution = uifactory.addTextElement("institution", "guidemo.flexi.form.institution", 256, personData.getInstitution(), formLayout); institution.setEnabled(inputMode); - if(inputMode){ + if(inputMode) { //submit only if in input mode submit = new FormSubmit("submit","submit"); formLayout.add(submit); } - - /* - * now the rules to hide unhide - */ - Set<FormItem> targets = new HashSet<FormItem>(); - targets.add(firstName); - targets.add(lastName); - targets.add(institution); - targets.add(submit); - - RulesFactory.createHideRule(checkbox, null, targets, formLayout); - RulesFactory.createShowRule(checkbox, "ison", targets, formLayout); } - - -} + + private void updateVisibility() { + boolean visible = checkbox.isAtLeastSelected(1); + firstName.setVisible(visible); + lastName.setVisible(visible); + institution.setVisible(visible); + submit.setVisible(visible); + } +} \ No newline at end of file diff --git a/src/main/java/org/olat/gui/demo/guidemo/GuiDemoFlexiFormMainController.java b/src/main/java/org/olat/gui/demo/guidemo/GuiDemoFlexiFormMainController.java index 3e5fcbc809c..6ade9dcbe2c 100644 --- a/src/main/java/org/olat/gui/demo/guidemo/GuiDemoFlexiFormMainController.java +++ b/src/main/java/org/olat/gui/demo/guidemo/GuiDemoFlexiFormMainController.java @@ -56,61 +56,18 @@ import org.olat.core.gui.dev.controller.SourceViewController; */ public class GuiDemoFlexiFormMainController extends BasicController { - private VelocityContainer mainVC; - private Map<String, ControllerCreator> demos = new HashMap<String, ControllerCreator>(); - List<String> demolinknames; + private final VelocityContainer mainVC; + private final Map<String, ControllerCreator> demos = new HashMap<>(); + private final List<String> demolinknames = new ArrayList<>(); private Controller demoController; private StackedPanel contentP; - private VelocityContainer content_sourceVC; + private VelocityContainer contentSourceVC; private Panel sourceP; - { - // create the demos - // could also be injected with spring - // - // for the order - demolinknames = new ArrayList<String>(); - // - demolinknames.add("guidemo_flexi_form_simpleform"); - demos.put("guidemo_flexi_form_simpleform", new ControllerCreator() { - public Controller createController(UserRequest ureq, WindowControl wControl) { - return new GuiDemoFlexiForm(ureq, wControl, null); - } - }); - demolinknames.add("guidemo_flexi_form_withchooser"); - demos.put("guidemo_flexi_form_withchooser", new ControllerCreator() { - public Controller createController(UserRequest ureq, WindowControl wControl) { - return new GuiDemoFlexiFormSubworkflow(ureq, wControl, null); - } - }); - demolinknames.add("guidemo_flexi_form_customlayout"); - demos.put("guidemo_flexi_form_customlayout", new ControllerCreator() { - public Controller createController(UserRequest ureq, WindowControl wControl) { - return new GuiDemoFlexiFormCustomlayout(ureq, wControl, null); - } - }); - demolinknames.add("guidemo_flexi_form_hideunhide"); - demos.put("guidemo_flexi_form_hideunhide", new ControllerCreator() { - public Controller createController(UserRequest ureq, WindowControl wControl) { - return new GuiDemoFlexiFormHideUnhide(ureq, wControl, null); - } - }); - demolinknames.add("guidemo_flexi_form_inline"); - demos.put("guidemo_flexi_form_inline", new ControllerCreator() { - public Controller createController(UserRequest ureq, WindowControl wControl) { - return new GuiDemoInlineEditingBasedOnFlexiForm(ureq, wControl); - } - }); - demolinknames.add("guidemo_flexi_form_advanced"); - demos.put("guidemo_flexi_form_advanced", new ControllerCreator() { - public Controller createController(UserRequest ureq, WindowControl wControl) { - return new GuiDemoFlexiFormAdvancedController(ureq, wControl); - } - }); - } public GuiDemoFlexiFormMainController(UserRequest ureq, WindowControl wControl) { super(ureq, wControl); mainVC = createVelocityContainer("flexiformdemos"); + initControllers(); for (String linkName : demolinknames) { Link tmpLink = LinkFactory.createLink(linkName, mainVC, this); @@ -119,9 +76,9 @@ public class GuiDemoFlexiFormMainController extends BasicController { mainVC.contextPut("demolinknames", demolinknames); - // all democontroller content goes in this panel + // all demo controllers content goes in this panel contentP = new SimpleStackedPanel("content"); - content_sourceVC = createVelocityContainer("content_source"); + contentSourceVC = createVelocityContainer("content_source"); mainVC.put("democontent", contentP); // String firstDemo = demolinknames.iterator().next(); @@ -134,13 +91,33 @@ public class GuiDemoFlexiFormMainController extends BasicController { ShrinkController sc = new ShrinkController(false, sourceVC, "toggle source"); sourceP.setContent(sc.getInitialComponent()); - content_sourceVC.put("content", mainVC); - content_sourceVC.put("source", sourceP); + contentSourceVC.put("content", mainVC); + contentSourceVC.put("source", sourceP); //add source view control - Controller sourceview = new SourceViewController(ureq, wControl, this.getClass(), content_sourceVC); - mainVC.put("sourceview", sourceview.getInitialComponent()); + Controller sourceview = new SourceViewController(ureq, wControl, this.getClass(), contentSourceVC); + mainVC.put("sourceview", sourceview.getInitialComponent()); - putInitialPanel(content_sourceVC); + putInitialPanel(contentSourceVC); + } + + private void initControllers() { + demolinknames.add("guidemo_flexi_form_simpleform"); + demos.put("guidemo_flexi_form_simpleform", (ureq, wControl) -> new GuiDemoFlexiForm(ureq, wControl, null)); + + demolinknames.add("guidemo_flexi_form_withchooser"); + demos.put("guidemo_flexi_form_withchooser", (ureq, wControl) -> new GuiDemoFlexiFormSubworkflow(ureq, wControl, null)); + + demolinknames.add("guidemo_flexi_form_customlayout"); + demos.put("guidemo_flexi_form_customlayout", (ureq, wControl) -> new GuiDemoFlexiFormCustomlayout(ureq, wControl, null)); + + demolinknames.add("guidemo_flexi_form_hideunhide"); + demos.put("guidemo_flexi_form_hideunhide", (ureq, wControl) -> new GuiDemoFlexiFormHideUnhide(ureq, wControl, null)); + + demolinknames.add("guidemo_flexi_form_inline"); + demos.put("guidemo_flexi_form_inline", (ureq, wControl) -> new GuiDemoInlineEditingBasedOnFlexiForm(ureq, wControl)); + + demolinknames.add("guidemo_flexi_form_advanced"); + demos.put("guidemo_flexi_form_advanced", (ureq, wControl) -> new GuiDemoFlexiFormAdvancedController(ureq, wControl)); } /** @@ -178,7 +155,5 @@ public class GuiDemoFlexiFormMainController extends BasicController { contentP.pushContent(demoController.getInitialComponent()); } } - } - } -- GitLab