Example usage for org.apache.wicket.ajax.form OnChangeAjaxBehavior OnChangeAjaxBehavior

List of usage examples for org.apache.wicket.ajax.form OnChangeAjaxBehavior OnChangeAjaxBehavior

Introduction

In this page you can find the example usage for org.apache.wicket.ajax.form OnChangeAjaxBehavior OnChangeAjaxBehavior.

Prototype

public OnChangeAjaxBehavior() 

Source Link

Document

Constructor.

Usage

From source file:org.obiba.onyx.quartz.editor.behavior.VariableNameBehavior.java

License:Open Source License

public VariableNameBehavior(final TextField<String> name, final TextField<String> variable,
        final Question parentQuestion, final Question question, final Category category) {

    variableNameDefined = StringUtils.isNotBlank(variable.getModelObject());

    if (!variableNameDefined) {

        variable.setOutputMarkupId(true);

        variable.setModelObject(/*from   w w  w  .j a v  a  2 s.  c om*/
                generateVariableName(parentQuestion, question, category, name.getModelObject()));
        variable.add(new AttributeModifier("class", true, new Model<String>("autoDefined")));
        final AjaxEventBehavior updateVariableNameBehavior = new OnChangeAjaxBehavior() {

            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                if (!variableNameDefined) {
                    variable.setModelObject(
                            generateVariableName(parentQuestion, question, category, name.getModelObject()));
                    target.addComponent(variable);
                }
            }
        };
        name.add(updateVariableNameBehavior);

        variable.add(new AjaxEventBehavior("onclick") {
            @Override
            protected void onEvent(AjaxRequestTarget target) {
                variable.setModelObject("");
                variable.add(new AttributeModifier("class", true, new Model<String>("userDefined")));
                variableNameDefined = true;
                target.addComponent(variable);
            }

            @Override
            public boolean isEnabled(Component component) {
                return !variableNameDefined;
            }
        });

    }

}

From source file:org.obiba.onyx.quartz.editor.category.MultipleChoiceCategoryHeaderPanel.java

License:Open Source License

@SuppressWarnings("serial")
public MultipleChoiceCategoryHeaderPanel(String id, final IModel<Questionnaire> questionnaireModel,
        final IModel<EditedQuestion> model) {
    super(id, model);
    setOutputMarkupId(true);/*from ww w  .  ja v a 2  s.com*/
    this.questionnaireModel = questionnaireModel;

    final Form<Question> form = new Form<Question>("form", new Model<Question>(model.getObject().getElement()));

    editedQuestion = model.getObject();
    question = model.getObject().getElement();

    choices = new LoadableDetachableModel<List<QuestionCategory>>() {

        private static final long serialVersionUID = 1L;

        @Override
        protected List<QuestionCategory> load() {
            List<QuestionCategory> missingQuestionCategories = question.getMissingQuestionCategories();
            List<QuestionCategory> correctQuestionCategories = new ArrayList<QuestionCategory>();
            for (QuestionCategory questionCategory : missingQuestionCategories) {
                boolean noAnswer = questionCategory.getCategory().isNoAnswer();
                boolean sharedIfLink = QuestionnaireSharedCategory.isSharedIfLink(questionCategory,
                        questionnaireModel.getObject());
                if (!sharedIfLink || noAnswer) {
                    correctQuestionCategories.add(questionCategory);
                    if (sharedIfLink && noAnswer) {
                        correctQuestionCategories.clear();
                        correctQuestionCategories.add(questionCategory);
                        return correctQuestionCategories;
                    }
                }
            }
            return correctQuestionCategories;
        }
    };

    requiredAnswer = new CheckBox("requiredAnswer", new Model<Boolean>());

    requiredAnswer.setLabel(new ResourceModel("RequiredAnswer"));
    form.add(requiredAnswer).add(new SimpleFormComponentLabel("requiredAnswerLabel", requiredAnswer));

    noAnswerCategoryModel = new Model<QuestionCategory>() {

        public QuestionCategory getObject() {
            return question.getNoAnswerQuestionCategory();
        }

        @Override
        public void setObject(QuestionCategory questionCategory) {
            super.setObject(questionCategory);
            question.setNoAnswerCategory(questionCategory == null ? null : questionCategory.getCategory());
        }
    };
    IChoiceRenderer<QuestionCategory> choicesRenderer = new ChoiceRenderer<QuestionCategory>("category.name");
    noAnswerCategoryDropDown = new DropDownChoice<QuestionCategory>("noAnswerCategoryDropDown",
            noAnswerCategoryModel, choices, choicesRenderer);
    noAnswerCategoryDropDown.setNullValid(true);
    noAnswerCategoryDropDown.setLabel(new ResourceModel("NoAnswer"));
    noAnswerCategoryDropDown.add(new OnChangeAjaxBehavior() {

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            // Do nothing, it is only to ajax update model when we change value in dropdown
        }

    });

    form.add(noAnswerCategoryDropDown)
            .add(new SimpleFormComponentLabel("noAnswerLabel", noAnswerCategoryDropDown));

    form.add(new HelpTooltipPanel("noAnswerHelp", new ResourceModel("NoAnswer.Tooltip")));

    minCountTextField = new TextField<Integer>("minCountTextField",
            new PropertyModel<Integer>(question, "minCount"));
    previousOrFirstMinValue = minCountTextField.getModelObject();
    minCountTextField.setLabel(new ResourceModel("Min"));
    minCountTextField.add(new OnChangeAjaxBehavior() {

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            // Do nothing, it is only to ajax update model when we change value
        }
    });
    SimpleFormComponentLabel minCountLabelComponent = new SimpleFormComponentLabel("minCountLabel",
            minCountTextField);

    maxCountTextField = new TextField<Integer>("maxCountTextField",
            new PropertyModel<Integer>(question, "maxCount"));
    maxCountTextField.setLabel(new ResourceModel("Max"));
    SimpleFormComponentLabel maxCountLabelComponent = new SimpleFormComponentLabel("maxCountLabel",
            maxCountTextField);

    form.add(minCountTextField, maxCountTextField, minCountLabelComponent, maxCountLabelComponent);
    form.add(new HelpTooltipPanel("minHelp", new ResourceModel("Min.Tooltip")));
    form.add(new HelpTooltipPanel("maxHelp", new ResourceModel("Max.Tooltip")));

    requiredAnswer.add(new OnChangeAjaxBehavior() {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            clickRequired(target);
        }
    });

    form.add(new IFormValidator() {

        @Override
        public void validate(@SuppressWarnings("hiding") Form<?> form) {
            Integer min = minCountTextField.getConvertedInput();
            Integer max = maxCountTextField.getConvertedInput();
            if (min != null && max != null && min > max) {
                form.error(new StringResourceModel("MinInfMax", MultipleChoiceCategoryHeaderPanel.this, null)
                        .getObject());
            }
            if (BooleanUtils.isTrue(requiredAnswer.getModelObject()) && min != null && min <= 0) {
                form.error(new StringResourceModel("MinMustBeMoreZero", MultipleChoiceCategoryHeaderPanel.this,
                        null).getObject());
            }
        }

        @Override
        public FormComponent<?>[] getDependentFormComponents() {
            return null;
        }
    });
    add(form);
}

From source file:org.obiba.onyx.quartz.editor.openAnswer.AudioOpenAnswerPanel.java

License:Open Source License

public AudioOpenAnswerPanel(String id, IModel<OpenAnswerDefinition> model, IModel<Category> categoryModel,
        IModel<Question> questionModel, final IModel<Questionnaire> questionnaireModel) {
    super(id, model);

    final Question question = questionModel.getObject();
    final Category category = categoryModel.getObject();
    final OpenAnswerDefinition openAnswer = model.getObject();

    initialName = model.getObject().getName();
    final TextField<String> name = new TextField<String>("name", new PropertyModel<String>(model, "name"));
    name.setLabel(new ResourceModel("Name"));
    name.add(new RequiredFormFieldBehavior());
    name.add(new PatternValidator(QuartzEditorPanel.ELEMENT_NAME_PATTERN));
    name.add(new AbstractValidator<String>() {
        @Override/*from  w  ww  . ja v  a2  s  .c  o m*/
        protected void onValidate(IValidatable<String> validatable) {
            if (!StringUtils.equals(initialName, validatable.getValue())) {
                boolean alreadyContains = false;
                if (category != null) {
                    Map<String, OpenAnswerDefinition> openAnswerDefinitionsByName = category
                            .getOpenAnswerDefinitionsByName();
                    alreadyContains = openAnswerDefinitionsByName.containsKey(validatable.getValue())
                            && openAnswerDefinitionsByName.get(validatable.getValue()) != openAnswer;
                }
                QuestionnaireFinder questionnaireFinder = QuestionnaireFinder
                        .getInstance(questionnaireModel.getObject());
                questionnaireModel.getObject().setQuestionnaireCache(null);
                OpenAnswerDefinition findOpenAnswerDefinition = questionnaireFinder
                        .findOpenAnswerDefinition(validatable.getValue());
                if (alreadyContains
                        || findOpenAnswerDefinition != null && findOpenAnswerDefinition != openAnswer) {
                    error(validatable, "OpenAnswerAlreadyExists");
                }
            }
        }
    });
    add(name).add(new SimpleFormComponentLabel("nameLabel", name));
    add(new HelpTooltipPanel("nameHelp", new ResourceModel("Name.Tooltip")));

    variable = new TextField<String>("variable", new MapModel<String>(
            new PropertyModel<Map<String, String>>(model, "variableNames"), question.getName()));
    variable.setLabel(new ResourceModel("Variable"));
    add(variable).add(new SimpleFormComponentLabel("variableLabel", variable));
    add(new HelpTooltipPanel("variableHelp", new ResourceModel("Variable.Tooltip")));

    if (category == null) {
        variableNameBehavior = new VariableNameBehavior(name, variable, question.getParentQuestion(), question,
                null) {
            @Override
            @SuppressWarnings("hiding")
            protected String generateVariableName(Question parentQuestion, Question question, Category category,
                    String name) {
                if (StringUtils.isBlank(name))
                    return "";
                if (category != null) {
                    return super.generateVariableName(parentQuestion, question, category, name);
                }
                String variableName = parentQuestion == null ? "" : parentQuestion.getName() + ".";
                if (question != null) {
                    variableName += question.getName() + "." + question.getName() + ".";
                }
                return variableName + StringUtils.trimToEmpty(name);
            }
        };
    } else {
        variableNameBehavior = new VariableNameBehavior(name, variable, question.getParentQuestion(), question,
                category);
    }

    add(variableNameBehavior);

    OpenAnswerDefinitionAudio openAnswerAudio = new OpenAnswerDefinitionAudio(openAnswer);

    samplingRateDropDown = new DropDownChoice<Rate>("samplingRate",
            new Model<Rate>(openAnswerAudio.getSamplingRate()), Arrays.asList(Rate.values()),
            new IChoiceRenderer<Rate>() {
                @Override
                public Object getDisplayValue(Rate rate) {
                    return new StringResourceModel("SamplingRate." + rate.toString(), AudioOpenAnswerPanel.this,
                            null).getString();
                }

                @Override
                public String getIdValue(Rate rate, int index) {
                    return rate.name();
                }
            });

    samplingRateDropDown.setLabel(new ResourceModel("SamplingRate"));
    samplingRateDropDown.add(new RequiredFormFieldBehavior());
    samplingRateDropDown.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            calculateResultingSize();
            target.addComponent(resultingSizeContainer);
        }
    });
    samplingRateDropDown.setNullValid(false);

    add(samplingRateDropDown).add(new SimpleFormComponentLabel("samplingRateLabel", samplingRateDropDown));
    add(new HelpTooltipPanel("samplingRateHelp", new ResourceModel("SamplingRate.Tooltip")));

    maxDurationField = new TextField<Integer>("maxDuration",
            new Model<Integer>(openAnswerAudio.getMaxDuration()));
    maxDurationField.setLabel(new ResourceModel("MaxDuration"));
    maxDurationField.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            calculateResultingSize();
            target.addComponent(resultingSizeContainer);
        }
    });
    add(maxDurationField).add(new SimpleFormComponentLabel("maxDurationLabel", maxDurationField));
    add(new HelpTooltipPanel("maxDurationHelp", new ResourceModel("MaxDuration.Tooltip")));

    resultingSizeContainer = new WebMarkupContainer("resultingSizeContainer");
    resultingSizeContainer.setOutputMarkupId(true);
    add(resultingSizeContainer);

    resultingSizeLabel = new Label("resultingSize", new Model<String>(""));
    resultingSizeContainer.add(resultingSizeLabel);
    calculateResultingSize();

    add(new HelpTooltipPanel("resultingSizeHelp", new ResourceModel("ResultingSize.Tooltip")));

}

From source file:org.obiba.onyx.quartz.editor.openAnswer.autocomplete.SuggestionVariableValuesPanel.java

License:Open Source License

public SuggestionVariableValuesPanel(String id, IModel<OpenAnswerDefinition> model,
        IModel<Questionnaire> questionnaireModel, FeedbackPanel feedbackPanel, FeedbackWindow feedbackWindow) {
    super(id, model);

    final OpenAnswerDefinitionSuggestion openAnswerSuggestion = new OpenAnswerDefinitionSuggestion(
            model.getObject());/* www.j  a  v a 2  s .  c  o  m*/

    List<String> datasources = new ArrayList<String>();
    for (Datasource ds : magmaInstanceProvider.getDatasources()) {
        datasources.add(ds.getName());
    }
    Collections.sort(datasources);

    datasource = new DropDownChoice<String>("datasource",
            new Model<String>(openAnswerSuggestion.getDatasource()), datasources);
    datasource.setLabel(new ResourceModel("Datasource"));
    datasource.setNullValid(false);
    datasource.setRequired(true);
    datasource.add(new RequiredFormFieldBehavior());
    datasource.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            openAnswerSuggestion.clearVariableValues();
            table.setModelObject(null);
            target.addComponent(table);
            target.addComponent(datasource);
            target.addComponent(variableTabbedPanel);
        }
    });
    add(datasource).add(new SimpleFormComponentLabel("datasourceLabel", datasource));

    IModel<List<String>> tableChoiceModel = new AbstractReadOnlyModel<List<String>>() {
        @Override
        public List<String> getObject() {
            if (datasource.getModelObject() == null) {
                return Collections.emptyList();
            }
            List<String> tables = new ArrayList<String>();
            for (ValueTable vt : magmaInstanceProvider.getDatasource(datasource.getModelObject())
                    .getValueTables()) {
                tables.add(datasource.getModelObject() + "." + vt.getName());
            }
            Collections.sort(tables);
            return tables;
        }
    };

    table = new DropDownChoice<String>("table",
            new PropertyModel<String>(new Model<OpenAnswerDefinitionSuggestion>(openAnswerSuggestion), "table"),
            tableChoiceModel, new IChoiceRenderer<String>() {
                @Override
                public Object getDisplayValue(String object) {
                    return getTableName(object);
                }

                @Override
                public String getIdValue(String object, int index) {
                    return object;
                }
            });
    table.setLabel(new ResourceModel("Table"));
    table.setOutputMarkupId(true);
    table.setNullValid(false);
    table.setRequired(true);
    table.add(new RequiredFormFieldBehavior());
    table.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            openAnswerSuggestion.clearVariableValues();
            // Set the entity type from the selected table.
            String path = table.getDefaultModelObjectAsString();
            String entityType = null;
            try {
                if (path != null) {
                    ValueTable valueTable = magmaInstanceProvider.resolveTable(path);
                    entityType = valueTable.getEntityType();
                }
            } catch (MagmaRuntimeException e) {
                // ignore
            }
            openAnswerSuggestion.setEntityType(entityType);
            target.addComponent(table);
            target.addComponent(variableTabbedPanel);
        }
    });
    add(table).add(new SimpleFormComponentLabel("tableLabel", table));

    Locale userLocale = Session.get().getLocale();
    List<ITab> tabs = new ArrayList<ITab>();
    for (final Locale locale : questionnaireModel.getObject().getLocales()) {
        AbstractTab tab = new AbstractTab(new Model<String>(locale.getDisplayLanguage(userLocale))) {
            @Override
            public Panel getPanel(String panelId) {
                return new VariablePanel(panelId, new VariableModel(openAnswerSuggestion, locale));
            }
        };
        tabs.add(new PanelCachingTab(tab));
    }

    variableTabbedPanel = new AjaxSubmitTabbedPanel("variableTabs", feedbackPanel, feedbackWindow, tabs);
    variableTabbedPanel.setVisible(!tabs.isEmpty());

    WebMarkupContainer variableTabsContainer = new WebMarkupContainer("variableTabsContainer");
    variableTabsContainer.setOutputMarkupId(true);
    variableTabsContainer.add(variableTabbedPanel);

    add(variableTabsContainer);

}

From source file:org.obiba.onyx.quartz.editor.openAnswer.OpenAnswerPanel.java

License:Open Source License

public OpenAnswerPanel(String id, IModel<OpenAnswerDefinition> model, IModel<Category> categoryModel,
        final IModel<Question> questionModel, final IModel<Questionnaire> questionnaireModel,
        IModel<LocaleProperties> localePropertiesModel, final FeedbackPanel feedbackPanel,
        final FeedbackWindow feedbackWindow) {
    super(id, model);
    this.questionModel = questionModel;
    this.questionnaireModel = questionnaireModel;
    this.localePropertiesModel = localePropertiesModel;
    this.feedbackPanel = feedbackPanel;
    this.feedbackWindow = feedbackWindow;

    final Question question = questionModel.getObject();
    final Category category = categoryModel.getObject();
    final OpenAnswerDefinition openAnswer = model.getObject();

    validatorWindow = new ModalWindow("validatorWindow");
    validatorWindow.setCssClassName("onyx");
    validatorWindow.setInitialWidth(850);
    validatorWindow.setInitialHeight(300);
    validatorWindow.setResizable(true);/*from  w  w w  .ja va2s  . c om*/
    validatorWindow.setTitle(new ResourceModel("Validator"));
    add(validatorWindow);

    initialName = model.getObject().getName();
    final TextField<String> name = new TextField<String>("name", new PropertyModel<String>(model, "name"));
    name.setLabel(new ResourceModel("Name"));
    name.add(new RequiredFormFieldBehavior());
    name.add(new PatternValidator(QuartzEditorPanel.ELEMENT_NAME_PATTERN));
    name.add(new AbstractValidator<String>() {
        @Override
        protected void onValidate(IValidatable<String> validatable) {
            if (!StringUtils.equals(initialName, validatable.getValue())) {
                boolean alreadyContains = false;
                if (category != null) {
                    Map<String, OpenAnswerDefinition> openAnswerDefinitionsByName = category
                            .getOpenAnswerDefinitionsByName();
                    alreadyContains = openAnswerDefinitionsByName.containsKey(validatable.getValue())
                            && openAnswerDefinitionsByName.get(validatable.getValue()) != openAnswer;
                }
                QuestionnaireFinder questionnaireFinder = QuestionnaireFinder
                        .getInstance(questionnaireModel.getObject());
                questionnaireModel.getObject().setQuestionnaireCache(null);
                OpenAnswerDefinition findOpenAnswerDefinition = questionnaireFinder
                        .findOpenAnswerDefinition(validatable.getValue());
                if (alreadyContains
                        || findOpenAnswerDefinition != null && findOpenAnswerDefinition != openAnswer) {
                    error(validatable, "OpenAnswerAlreadyExists");
                }
            }
        }
    });
    add(name).add(new SimpleFormComponentLabel("nameLabel", name));
    add(new HelpTooltipPanel("nameHelp", new ResourceModel("Name.Tooltip")));

    variable = new TextField<String>("variable", new MapModel<String>(
            new PropertyModel<Map<String, String>>(model, "variableNames"), question.getName()));
    variable.setLabel(new ResourceModel("Variable"));
    add(variable).add(new SimpleFormComponentLabel("variableLabel", variable));
    add(new HelpTooltipPanel("variableHelp", new ResourceModel("Variable.Tooltip")));

    if (category == null) {
        variableNameBehavior = new VariableNameBehavior(name, variable, question.getParentQuestion(), question,
                null) {
            @Override
            @SuppressWarnings("hiding")
            protected String generateVariableName(Question parentQuestion, Question question, Category category,
                    String name) {
                if (StringUtils.isBlank(name))
                    return "";
                if (category != null) {
                    return super.generateVariableName(parentQuestion, question, category, name);
                }
                String variableName = parentQuestion == null ? "" : parentQuestion.getName() + ".";
                if (question != null) {
                    variableName += question.getName() + "." + question.getName() + ".";
                }
                return variableName + StringUtils.trimToEmpty(name);
            }
        };
    } else {
        variableNameBehavior = new VariableNameBehavior(name, variable, question.getParentQuestion(), question,
                category);
    }

    add(variableNameBehavior);

    List<DataType> typeChoices = new ArrayList<DataType>(Arrays.asList(DataType.values()));
    typeChoices.remove(DataType.BOOLEAN);
    typeChoices.remove(DataType.DATA);
    dataTypeDropDown = new DropDownChoice<DataType>("dataType", new PropertyModel<DataType>(model, "dataType"),
            typeChoices, new IChoiceRenderer<DataType>() {
                @Override
                public Object getDisplayValue(DataType type) {
                    return new StringResourceModel("DataType." + type, OpenAnswerPanel.this, null).getString();
                }

                @Override
                public String getIdValue(DataType type, int index) {
                    return type.name();
                }
            });

    dataTypeDropDown.setLabel(new ResourceModel("DataType"));
    dataTypeDropDown.add(new RequiredFormFieldBehavior());
    dataTypeDropDown.setNullValid(false);

    add(dataTypeDropDown).add(new SimpleFormComponentLabel("dataTypeLabel", dataTypeDropDown));
    // add(new HelpTooltipPanel("dataTypeHelp", new ResourceModel("DataType.Tooltip")));

    TextField<String> unit = new TextField<String>("unit", new PropertyModel<String>(model, "unit"));
    unit.setLabel(new ResourceModel("Unit"));
    add(unit).add(new SimpleFormComponentLabel("unitLabel", unit));
    add(new HelpTooltipPanel("unitHelp", new ResourceModel("Unit.Tooltip")));

    PatternValidator numericPatternValidator = new PatternValidator("\\d*");
    // ui Arguments
    Integer size = openAnswer.getInputSize();
    sizeField = new TextField<String>("size", new Model<String>(size == null ? null : String.valueOf(size)));
    sizeField.add(numericPatternValidator);
    sizeField.setLabel(new ResourceModel("SizeLabel"));
    add(new SimpleFormComponentLabel("sizeLabel", sizeField));
    add(sizeField);

    Integer rows = openAnswer.getInputNbRows();
    rowsField = new TextField<String>("rows", new Model<String>(rows == null ? null : String.valueOf(rows)));
    rowsField.add(numericPatternValidator);
    rowsField.setLabel(new ResourceModel("RowsLabel"));
    add(new SimpleFormComponentLabel("rowsLabel", rowsField));
    add(rowsField);

    localePropertiesUtils.load(localePropertiesModel.getObject(), questionnaireModel.getObject(), openAnswer);

    Map<String, Boolean> visibleStates = new HashMap<String, Boolean>();
    if (openAnswer.isSuggestionAnswer()) {
        for (String item : new OpenAnswerDefinitionSuggestion(openAnswer).getSuggestionItems()) {
            visibleStates.put(item, false);
        }
    }
    add(labelsPanel = new LabelsPanel("labels", localePropertiesModel, model, feedbackPanel, feedbackWindow,
            null, visibleStates));

    CheckBox requiredCheckBox = new CheckBox("required", new PropertyModel<Boolean>(model, "required"));
    requiredCheckBox.setLabel(new ResourceModel("AnswerRequired"));
    add(requiredCheckBox);
    add(new SimpleFormComponentLabel("requiredLabel", requiredCheckBox));

    // min/max validators
    String maxValue = null, minValue = null, patternValue = null;
    for (IDataValidator<?> dataValidator : openAnswer.getDataValidators()) {
        IValidator<?> validator = dataValidator.getValidator();
        if (validator instanceof RangeValidator<?>) {
            RangeValidator<?> rangeValidator = (RangeValidator<?>) validator;
            Object minimum = rangeValidator.getMinimum();
            Object maximum = rangeValidator.getMaximum();
            if (dataValidator.getDataType() == DataType.DATE) {
                if (minimum != null)
                    minValue = onyxSettings.getDateFormat().format((Date) minimum);
                if (maximum != null)
                    maxValue = onyxSettings.getDateFormat().format((Date) maximum);
            } else {
                if (minimum != null)
                    minValue = String.valueOf(minimum);
                if (maximum != null)
                    maxValue = String.valueOf(maximum);
            }
        } else if (validator instanceof StringValidator.MaximumLengthValidator) {
            int maximum = ((StringValidator.MaximumLengthValidator) validator).getMaximum();
            if (maximum > 0)
                maxValue = String.valueOf(maximum);
        } else if (validator instanceof MaximumValidator<?>) {
            Object maximum = ((MaximumValidator<?>) validator).getMaximum();
            if (dataValidator.getDataType() == DataType.DATE) {
                if (maximum != null)
                    maxValue = onyxSettings.getDateFormat().format((Date) maximum);
            } else {
                if (maximum != null)
                    maxValue = String.valueOf(maximum);
            }
        } else if (validator instanceof StringValidator.MinimumLengthValidator) {
            int minimum = ((StringValidator.MinimumLengthValidator) validator).getMinimum();
            if (minimum > 0)
                minValue = String.valueOf(minimum);
        } else if (validator instanceof MinimumValidator<?>) {
            Object minimum = ((MinimumValidator<?>) validator).getMinimum();
            if (dataValidator.getDataType() == DataType.DATE) {
                if (minimum != null)
                    minValue = onyxSettings.getDateFormat().format((Date) minimum);
            } else {
                if (minimum != null)
                    minValue = String.valueOf(minimum);
            }
        } else if (validator instanceof PatternValidator) {
            patternValue = ((PatternValidator) validator).getPattern().toString();
        }
    }

    patternField = new TextField<String>("patternValidator", new Model<String>(patternValue));
    patternField.setLabel(new ResourceModel("PatternLabel"));
    patternField.setOutputMarkupId(true);
    add(new SimpleFormComponentLabel("patternLabel", patternField));
    add(patternField);

    minMaxContainer = new WebMarkupContainer("minMaxContainer");
    minMaxContainer.setOutputMarkupId(true);
    add(minMaxContainer);

    minLength = new TextField<String>("minLength", new Model<String>(minValue), String.class);
    minLength.setLabel(new ResourceModel("Minimum.length"));
    minMaxContainer.add(minLength);

    maxLength = new TextField<String>("maxLength", new Model<String>(maxValue), String.class);
    maxLength.setLabel(new ResourceModel("Maximum.length"));
    minMaxContainer.add(maxLength);

    minNumeric = new TextField<String>("minNumeric", new Model<String>(minValue), String.class);
    minNumeric.setLabel(new ResourceModel("Minimum"));
    minNumeric.add(numericPatternValidator);
    minMaxContainer.add(minNumeric);

    maxNumeric = new TextField<String>("maxNumeric", new Model<String>(maxValue), String.class);
    maxNumeric.setLabel(new ResourceModel("Maximum"));
    maxNumeric.add(numericPatternValidator);
    minMaxContainer.add(maxNumeric);

    PatternValidator decimalPatternValidator = new PatternValidator("\\d*(\\.\\d+)?");
    minDecimal = new TextField<String>("minDecimal", new Model<String>(minValue), String.class);
    minDecimal.setLabel(new ResourceModel("Minimum"));
    minDecimal.add(decimalPatternValidator);
    minMaxContainer.add(minDecimal);

    maxDecimal = new TextField<String>("maxDecimal", new Model<String>(maxValue), String.class);
    maxDecimal.setLabel(new ResourceModel("Maximum"));
    maxDecimal.add(decimalPatternValidator);
    minMaxContainer.add(maxDecimal);

    String patternStr = onyxSettings.getDateFormat().toPattern();

    beforeDate = new TextField<String>("beforeDate", new Model<String>(maxValue), String.class);
    beforeDate.setLabel(new Model<String>(
            new StringResourceModel("Before", this, null).getObject() + " (" + patternStr + ")"));
    minMaxContainer.add(beforeDate);

    afterDate = new TextField<String>("afterDate", new Model<String>(minValue), String.class);
    afterDate.setLabel(new Model<String>(
            new StringResourceModel("After", this, null).getObject() + " (" + patternStr + ")"));
    minMaxContainer.add(afterDate);

    minMaxContainer.add(minimumLabel = new SimpleFormComponentLabel("minimumLabel", minLength));
    minMaxContainer.add(maximumLabel = new SimpleFormComponentLabel("maximumLabel", maxLength));

    setMinMaxLabels(dataTypeDropDown.getModelObject());

    add(validators = new OnyxEntityList<ComparingDataSource>("validators", new ValidationDataSourcesProvider(),
            new ValidationDataSourcesColumnProvider(), new ResourceModel("Validators")));

    AjaxLink<Void> addValidator = new AjaxLink<Void>("addValidator") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            if (dataTypeDropDown.getModelObject() == null) {
                info(new StringResourceModel("SelectDataTypeFirst", OpenAnswerPanel.this, null).getString());
                feedbackWindow.setContent(feedbackPanel);
                feedbackWindow.show(target);
            } else {
                validatorWindow.setContent(new ValidationDataSourceWindow("content",
                        new Model<ComparingDataSource>(), questionModel, questionnaireModel,
                        dataTypeDropDown.getModelObject(), validatorWindow) {
                    @Override
                    protected void onSave(@SuppressWarnings("hiding") AjaxRequestTarget target,
                            ComparingDataSource comparingDataSource) {
                        openAnswer.addValidationDataSource(comparingDataSource);
                        target.addComponent(validators);
                    }
                });
                validatorWindow.show(target);
            }
        }
    };
    addValidator.setOutputMarkupId(true);
    add(addValidator.add(new Image("img", Images.ADD)));

    dataTypeDropDown.add(new OnChangeAjaxBehavior() {

        @SuppressWarnings("incomplete-switch")
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            setFieldType();
            String value = dataTypeDropDown.getValue(); // use value because model is not set if validation error
            DataType valueOf = DataType.valueOf(value);
            if (value != null) {
                OpenAnswerDefinition openAnswerDefinition = (OpenAnswerDefinition) getDefaultModelObject();
                for (Data data : openAnswerDefinition.getDefaultValues()) {

                    switch (valueOf) {
                    case DATE:
                        try {
                            onyxSettings.getDateFormat().parse(data.getValueAsString());
                        } catch (ParseException nfe) {
                            error(new StringResourceModel("InvalidCastType", OpenAnswerPanel.this, null)
                                    .getObject());
                            showFeedbackErrorAndReset(target);
                            return;
                        }
                        break;
                    case DECIMAL:
                        try {
                            Double.parseDouble(data.getValueAsString());
                        } catch (NumberFormatException nfe) {
                            error(new StringResourceModel("InvalidCastType", OpenAnswerPanel.this, null)
                                    .getObject());
                            showFeedbackErrorAndReset(target);
                            return;
                        }
                        break;
                    case INTEGER:
                        if (data.getType() == DataType.DECIMAL) {
                            Double d = data.getValue();
                            if (d != d.longValue()) {
                                error(new StringResourceModel("InvalidCastType", OpenAnswerPanel.this, null)
                                        .getObject());
                                showFeedbackErrorAndReset(target);
                                return;
                            }
                        } else {
                            try {
                                Long.parseLong(data.getValueAsString());
                            } catch (NumberFormatException nfe) {
                                error(new StringResourceModel("InvalidCastType", OpenAnswerPanel.this, null)
                                        .getObject());
                                showFeedbackErrorAndReset(target);
                                return;
                            }
                        }
                        break;
                    case TEXT:
                        break;
                    }
                }
                for (Data data : openAnswerDefinition.getDefaultValues()) {
                    switch (valueOf) {
                    case DATE:
                        try {
                            data.setTypeAndValue(valueOf,
                                    onyxSettings.getDateFormat().parse(data.getValueAsString()));
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                        break;
                    case DECIMAL:
                        data.setTypeAndValue(valueOf, Double.parseDouble(data.getValueAsString()));
                        break;
                    case INTEGER:
                        if (data.getType() == DataType.DECIMAL) {
                            data.setTypeAndValue(valueOf, ((Double) data.getValue()).longValue());
                        } else {
                            data.setTypeAndValue(valueOf, Integer.parseInt(data.getValueAsString()));
                        }
                        break;
                    case TEXT:
                        data.setTypeAndValue(valueOf,
                                data.getType() == DataType.DATE
                                        ? onyxSettings.getDateFormat().format(data.getValue())
                                        : data.getValueAsString());
                        break;
                    }
                }
            }
            setMinMaxLabels(value == null ? null : valueOf);
            target.addComponent(minMaxContainer);
            target.addComponent(patternField);
            defaultValuesList.refreshList(target);
        }

        private void showFeedbackErrorAndReset(AjaxRequestTarget target) {
            dataTypeDropDown.setModelObject(openAnswer.getDefaultValues().get(0).getType());
            target.addComponent(dataTypeDropDown);
            OpenAnswerPanel.this.feedbackWindow.setContent(OpenAnswerPanel.this.feedbackPanel);
            OpenAnswerPanel.this.feedbackWindow.show(target);
        }
    });

    final IModel<String> addDefaultValuesModel = new Model<String>();

    List<ITab> tabs = new ArrayList<ITab>();
    tabs.add(new AbstractTab(new ResourceModel("Add.simple")) {
        @Override
        public Panel getPanel(String panelId) {
            return new SimpleAddPanel(panelId, addDefaultValuesModel);
        }
    });
    tabs.add(new AbstractTab(new ResourceModel("Add.bulk")) {
        @Override
        public Panel getPanel(String panelId) {
            return new BulkAddPanel(panelId, addDefaultValuesModel);
        }
    });
    add(new AjaxTabbedPanel("addTabs", tabs));

    defaultValuesList = new SortableList<Data>("defaultValues", openAnswer.getDefaultValues(), true) {

        @Override
        public Component getItemTitle(@SuppressWarnings("hiding") String id, Data data) {
            return new Label(id,
                    data.getType() == DataType.DATE ? onyxSettings.getDateFormat().format(data.getValue())
                            : data.getValueAsString());
        }

        @Override
        public void editItem(Data t, AjaxRequestTarget target) {

        }

        @SuppressWarnings("unchecked")
        @Override
        public void deleteItem(final Data data, AjaxRequestTarget target) {
            ((OpenAnswerDefinition) OpenAnswerPanel.this.getDefaultModelObject()).removeDefaultData(data);
            for (Locale locale : OpenAnswerPanel.this.localePropertiesModel.getObject().getLocales()) {
                List<KeyValue> list = OpenAnswerPanel.this.localePropertiesModel.getObject()
                        .getElementLabels(openAnswer).get(locale);
                Collection<KeyValue> toDelete = Collections2.filter(list, new Predicate<KeyValue>() {

                    @Override
                    public boolean apply(KeyValue input) {
                        return input.getKey().equals(data.getValue().toString());
                    }

                });
                list.remove(toDelete.iterator().next());
            }
            OpenAnswerPanel.this.addOrReplace(
                    labelsPanel = new LabelsPanel("labels", OpenAnswerPanel.this.localePropertiesModel,
                            (IModel<OpenAnswerDefinition>) OpenAnswerPanel.this.getDefaultModel(),
                            OpenAnswerPanel.this.feedbackPanel, OpenAnswerPanel.this.feedbackWindow));
            target.addComponent(labelsPanel);
            refreshList(target);
        }

        @Override
        public Button[] getButtons() {
            return null;
        }

    };
    add(defaultValuesList);
    add(new HelpTooltipPanel("defaultValuesHelp", new ResourceModel("DefaultValues.Tooltip")));
}

From source file:org.obiba.onyx.quartz.editor.openAnswer.validation.ValidationDataSourceWindow.java

License:Open Source License

public ValidationDataSourceWindow(String id, IModel<ComparingDataSource> model,
        final IModel<Question> questionModel, final IModel<Questionnaire> questionnaireModel,
        final DataType dataType, final ModalWindow modalWindow) {
    super(id, model);
    this.dataType = dataType;

    final ValueType valueType = VariableUtils.convertToValueType(dataType);

    add(CSSPackageResource.getHeaderContribution(ValidationDataSourceWindow.class,
            "ValidationDataSourceWindow.css"));

    variableWindow = new ModalWindow("variableWindow");
    variableWindow.setCssClassName("onyx");
    variableWindow.setInitialWidth(950);
    variableWindow.setInitialHeight(540);
    variableWindow.setResizable(true);//from   w w  w .java  2  s. com
    variableWindow.setTitle(new ResourceModel("Variable"));
    add(variableWindow);

    final Questionnaire questionnaire = questionnaireModel.getObject();

    final OpenAnswerValidator validator = new OpenAnswerValidator();
    if (model.getObject() != null) {
        ComparingDataSource comparingDataSource = model.getObject();
        validator.setOperator(comparingDataSource.getComparisonOperator());
        IDataSource dataSourceRight = comparingDataSource.getDataSourceRight();
        if (dataSourceRight instanceof VariableDataSource) {
            VariableDataSource variableDataSource = (VariableDataSource) dataSourceRight;
            if (questionnaire.getName().equals(variableDataSource.getTableName())) {
                try {
                    validator.setVariable(questionnaire.getVariable(variableDataSource.getVariableName()));
                    validator.setType(Type.VARIABLE);
                } catch (IllegalArgumentException e) {
                    // not found in this questionnaire
                }
            }
            if (validator.getType() == null) { // not found yet
                Variable variable = variableUtils.findVariable(variableDataSource);
                if (variable != null) {
                    try {
                        validator.setVariable(questionnaire.getVariable(variable.getName()));
                        validator.setType(Type.VARIABLE);
                    } catch (IllegalArgumentException e) {
                        // not found
                        Question question = VariableUtils.findQuestion(variable,
                                QuestionnaireFinder.getInstance(questionnaire));
                        validator.setType(Type.QUESTION_CATEGORY);
                        validator.setQuestion(question);
                        Category category = VariableUtils.findCategory(variable, question);
                        validator.setCategory(category);
                        validator.setOpenAnswer(VariableUtils.findOpenAnswer(variable, category));
                    }
                }
            }
        } else if (dataSourceRight instanceof JavascriptDataSource) {
            JavascriptDataSource javascriptDataSource = (JavascriptDataSource) dataSourceRight;
            validator.setType(JAVASCRIPT);
            validator.setScript(javascriptDataSource.getScript());
        }
    }

    feedbackPanel = new FeedbackPanel("content");
    feedbackWindow = new FeedbackWindow("feedback");
    feedbackWindow.setOutputMarkupId(true);

    add(feedbackWindow);

    add(form = new Form<OpenAnswerValidator>("form", new Model<OpenAnswerValidator>(validator)));
    form.setMultiPart(false);

    IChoiceRenderer<ComparisonOperator> operatorRenderer = new IChoiceRenderer<ComparisonOperator>() {
        @Override
        public String getIdValue(ComparisonOperator operator, int index) {
            return operator.name();
        }

        @Override
        public Object getDisplayValue(ComparisonOperator operator) {
            return new StringResourceModel("Operator." + operator, ValidationDataSourceWindow.this, null)
                    .getString();
        }
    };

    List<ComparisonOperator> comparisonOperatorAsList = null;
    if (dataType == DataType.TEXT) {
        comparisonOperatorAsList = Arrays.asList(ComparisonOperator.eq, ComparisonOperator.ne,
                ComparisonOperator.in);
    } else {
        comparisonOperatorAsList = Arrays.asList(ComparisonOperator.values());
    }
    final DropDownChoice<ComparisonOperator> operator = new DropDownChoice<ComparisonOperator>("operator",
            new PropertyModel<ComparisonOperator>(form.getModel(), "operator"), comparisonOperatorAsList,
            operatorRenderer);
    form.add(operator.setLabel(new ResourceModel("Operator")).setRequired(true))
            .add(new SimpleFormComponentLabel("operatorLabel", operator));

    final RadioGroup<Type> validationType = new RadioGroup<Type>("validationType",
            new PropertyModel<Type>(form.getModel(), "type"));
    form.add(validationType.setLabel(new ResourceModel("Variable")).setRequired(true));

    final Radio<Type> questionType = new Radio<Type>("questionType", new Model<Type>(QUESTION_CATEGORY));
    questionType.setLabel(new ResourceModel("QuestionType"));
    validationType.add(questionType).add(new SimpleFormComponentLabel("questionTypeLabel", questionType));

    final WebMarkupContainer questionTypeContainer = new WebMarkupContainer("questionTypeContainer");
    questionTypeContainer.setOutputMarkupId(true);
    validationType.add(questionTypeContainer);

    final WebMarkupContainer questionConditionContainer = new WebMarkupContainer("questionConditionContainer");
    questionConditionContainer.setVisible(validator.getType() == QUESTION_CATEGORY);
    questionTypeContainer.add(questionConditionContainer);

    if (questionnaire.getQuestionnaireCache() == null) {
        QuestionnaireFinder.getInstance(questionnaire).buildQuestionnaireCache();
    }

    List<Question> questions = new ArrayList<Question>(
            questionnaire.getQuestionnaireCache().getQuestionCache().values());
    Collections.sort(questions, new QuestionnaireElementComparator());
    final Multimap<Question, Category> questionCategories = LinkedHashMultimap.create();
    final Multimap<Category, OpenAnswerDefinition> categoryOpenAnswer = LinkedHashMultimap.create();
    for (Question q : questions) {
        if (!q.equals(questionModel.getObject()) && q.getType() != QuestionType.BOILER_PLATE) {
            final List<Category> findCategories = findCategories(q);
            for (Category category : findCategories) {
                categoryOpenAnswer.putAll(category, category.getOpenAnswerDefinitionsByName().values());
            }
            questionCategories.putAll(q, findCategories);
        }
    }

    final DropDownChoice<Question> questionName = new DropDownChoice<Question>("question",
            new PropertyModel<Question>(form.getModel(), "question"),
            new ArrayList<Question>(questionCategories.keySet()), new QuestionnaireElementNameRenderer()) {
        @Override
        public boolean isRequired() {
            return validationType.getModelObject() == QUESTION_CATEGORY;
        }
    };

    questionName.setLabel(new ResourceModel("Question"));
    questionConditionContainer.add(questionName)
            .add(new SimpleFormComponentLabel("questionLabel", questionName));

    final List<Category> categories = questionName.getModelObject() == null ? new ArrayList<Category>()
            : new ArrayList<Category>(questionCategories.get(questionName.getModelObject()));

    final DropDownChoice<Category> categoryName = new DropDownChoice<Category>("category",
            new PropertyModel<Category>(form.getModel(), "category"), categories,
            new QuestionnaireElementNameRenderer()) {
        @Override
        public boolean isRequired() {
            return validationType.getModelObject() == QUESTION_CATEGORY;
        }
    };
    categoryName.setLabel(new ResourceModel("Category"));
    questionConditionContainer.add(categoryName)
            .add(new SimpleFormComponentLabel("categoryLabel", categoryName));

    final List<OpenAnswerDefinition> openAnswers = categoryName.getModelObject() == null
            ? new ArrayList<OpenAnswerDefinition>()
            : new ArrayList<OpenAnswerDefinition>(categoryOpenAnswer.get(categoryName.getModelObject()));

    final DropDownChoice<OpenAnswerDefinition> openAnswerName = new DropDownChoice<OpenAnswerDefinition>(
            "openAnswer", new PropertyModel<OpenAnswerDefinition>(form.getModel(), "openAnswer"), openAnswers,
            new QuestionnaireElementNameRenderer()) {
        @Override
        public boolean isRequired() {
            return validationType.getModelObject() == QUESTION_CATEGORY;
        }
    };

    questionName.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            categories.clear();
            openAnswers.clear();
            categories.addAll(questionName.getModelObject() == null ? new ArrayList<Category>()
                    : new ArrayList<Category>(questionCategories.get(questionName.getModelObject())));
            openAnswers.addAll(categories.isEmpty() ? new ArrayList<OpenAnswerDefinition>()
                    : new ArrayList<OpenAnswerDefinition>(categoryOpenAnswer.get(categories.get(0))));
            target.addComponent(categoryName);
            target.addComponent(openAnswerName);
        }
    });

    categoryName.add(new OnChangeAjaxBehavior() {

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            openAnswers.clear();
            openAnswers.addAll(categoryName.getModelObject() == null ? new ArrayList<OpenAnswerDefinition>()
                    : new ArrayList<OpenAnswerDefinition>(
                            categoryOpenAnswer.get(categoryName.getModelObject())));
            target.addComponent(openAnswerName);
        }
    });

    openAnswerName.setLabel(new ResourceModel("OpenAnswer"));
    questionConditionContainer.add(openAnswerName)
            .add(new SimpleFormComponentLabel("openAnswerLabel", openAnswerName));

    Radio<Type> variableType = new Radio<Type>("variableType", new Model<Type>(VARIABLE));
    variableType.setLabel(new ResourceModel("Variable"));
    validationType.add(variableType).add(new SimpleFormComponentLabel("variableTypeLabel", variableType));

    final WebMarkupContainer variableTypeContainer = new WebMarkupContainer("variableTypeContainer");
    variableTypeContainer.setOutputMarkupId(true);
    validationType.add(variableTypeContainer);

    final WebMarkupContainer variableContainer = new WebMarkupContainer("variableContainer");
    variableContainer.setVisible(validator.getType() == VARIABLE);
    variableTypeContainer.add(variableContainer);

    final List<Variable> variables = new ArrayList<Variable>(
            Collections2.filter(questionnaire.getVariables(), new Predicate<Variable>() {
                @Override
                public boolean apply(Variable v) {
                    // Filter for text when the operator is 'IN'
                    if (validator.getOperator() != null
                            && validator.getOperator().equals(ComparisonOperator.in)) {
                        return v.getValueType().equals(VariableUtils.convertToValueType(DataType.TEXT));
                    }
                    return v.getValueType().equals(valueType);
                }
            }));

    final DropDownChoice<Variable> variableDropDown = new DropDownChoice<Variable>("variable",
            new PropertyModel<Variable>(form.getModel(), "variable"), variables, new VariableRenderer()) {
        @Override
        public boolean isRequired() {
            return validationType.getModelObject() == VARIABLE;
        }
    };
    variableDropDown.setLabel(new ResourceModel("Variable")).setOutputMarkupId(true);
    variableContainer.add(variableDropDown);

    final WebMarkupContainer previewVariableVisibility = new WebMarkupContainer("previewVariableVisibility");
    variableContainer.add(previewVariableVisibility.setOutputMarkupId(true));

    final Image previewVariable = new Image("previewVariable", Images.ZOOM);
    previewVariable.add(new AttributeModifier("title", true, new ResourceModel("Preview")));
    previewVariable.setVisible(variableDropDown.getModelObject() != null);
    previewVariableVisibility.add(previewVariable);

    final Label previewScript = new Label("previewScript", variableDropDown.getModelObject() == null ? ""
            : variableDropDown.getModelObject().getAttributeStringValue("script"));
    previewScript.add(new SyntaxHighlighterBehavior());
    previewScript.add(new AttributeAppender("style", true, new Model<String>("display: none;"), " "));
    previewVariableVisibility.add(previewScript);

    final Map<String, Object> tooltipCfg = new HashMap<String, Object>();
    tooltipCfg.put("delay", 100);
    tooltipCfg.put("showURL", false);
    tooltipCfg.put("top", -30);
    tooltipCfg.put("bodyHandler",
            "function() { return $(\"#" + previewScript.getMarkupId(true) + "\").html(); }");
    previewVariable.add(new TooltipBehavior(null, tooltipCfg));

    variableContainer.add(new AjaxLink<Void>("newVariable") {
        @Override
        public void onClick(AjaxRequestTarget target) {

            @SuppressWarnings({ "rawtypes", "unchecked" })
            VariablePanel variablePanel = new VariablePanel("content", new Model(null), questionnaireModel,
                    valueType) {
                @Override
                public void onSave(@SuppressWarnings("hiding") AjaxRequestTarget target,
                        Variable createdVariable) {
                    variables.add(createdVariable);
                    questionnaire.addVariable(createdVariable);
                    variableDropDown.setModelObject(createdVariable);
                    previewVariable.setVisible(true);
                    previewScript.setDefaultModelObject(createdVariable.getAttributeStringValue("script"));
                    variableWindow.close(target);
                    target.addComponent(variableDropDown);
                    target.addComponent(previewVariableVisibility);
                }

                @Override
                public void onCancel(@SuppressWarnings("hiding") AjaxRequestTarget target) {
                    variableWindow.close(target);
                }
            };
            variableWindow.setContent(variablePanel);
            variableWindow.show(target);
        }
    }.add(new Image("newVariableImg", Images.ADD))
            .add(new AttributeModifier("title", true, new ResourceModel("NewVariable"))));

    variableDropDown.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            Variable variable = variableDropDown.getModelObject();
            previewVariable.setVisible(variable != null);
            previewScript.setDefaultModelObject(
                    variable == null ? null : variable.getAttributeStringValue("script"));
            target.addComponent(previewVariableVisibility);
        }
    });

    Radio<Type> javascriptType = new Radio<Type>("javascriptType", new Model<Type>(JAVASCRIPT));
    javascriptType.setLabel(new ResourceModel("JavascriptType"));
    validationType.add(javascriptType).add(new SimpleFormComponentLabel("javascriptTypeLabel", javascriptType));

    final TextArea<String> javascriptField = new TextArea<String>("javascriptField",
            new PropertyModel<String>(validator, "script"));
    javascriptField.setOutputMarkupPlaceholderTag(true);
    javascriptField.setVisible(validator.getType() == JAVASCRIPT);
    validationType.add(javascriptField);

    javascriptField.add(new IValidator<String>() {

        @Override
        public void validate(final IValidatable<String> validatable) {
            JavascriptUtils.compile(validatable.getValue(), questionModel.getObject().getName(),
                    ValidationDataSourceWindow.this, form);
        }
    });

    validationType.add(new AjaxFormChoiceComponentUpdatingBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            Type type = validationType.getModelObject();
            switch (type) {
            case QUESTION_CATEGORY:
                variableDropDown.setModelObject(null);
                javascriptField.setModelObject(null);
                break;
            case VARIABLE:
                questionName.setModelObject(null);
                categoryName.setModelObject(null);
                openAnswerName.setModelObject(null);
                javascriptField.setModelObject(null);
                break;
            case JAVASCRIPT:
                variableDropDown.setModelObject(null);
                questionName.setModelObject(null);
                categoryName.setModelObject(null);
                openAnswerName.setModelObject(null);
                break;
            }
            questionConditionContainer.setVisible(type == QUESTION_CATEGORY);
            variableContainer.setVisible(type == VARIABLE);
            javascriptField.setVisible(type == JAVASCRIPT);
            target.addComponent(questionTypeContainer);
            target.addComponent(variableTypeContainer);
            target.addComponent(javascriptField);
        }
    });

    form.add(new SaveCancelPanel("saveCancel", form) {
        @Override
        protected void onSave(AjaxRequestTarget target, Form<?> form1) {

            IDataSource dataSource = null;
            switch (validator.getType()) {
            case QUESTION_CATEGORY:
                Question question = validator.getQuestion();
                OpenAnswerDefinition openAnswer = validator.getOpenAnswer();
                String variableName = openAnswer.getVariableName(question.getName());
                if (StringUtils.isNotBlank(variableName)) {
                    dataSource = new VariableDataSource(questionnaire.getName() + ":" + variableName);
                } else {
                    dataSource = new VariableDataSource(questionnaire.getName() + ":" + question.getName() + "."
                            + validator.getCategory().getName() + "." + openAnswer.getName());
                }
                break;
            case VARIABLE:
                dataSource = new VariableDataSource(
                        questionnaire.getName() + ":" + validator.getVariable().getName());
                break;
            case JAVASCRIPT:
                dataSource = new JavascriptDataSource(validator.getScript(),
                        VariableUtils.convertToValueType(dataType).getName(), questionnaire.getName());
                ((JavascriptDataSource) dataSource)
                        .setSequence(validator.getOperator() == ComparisonOperator.in);
                break;
            }

            ComparingDataSource comparingDataSource = new ComparingDataSource(null, validator.getOperator(),
                    dataSource);
            ValidationDataSourceWindow.this.onSave(target, comparingDataSource);
            modalWindow.close(target);
        }

        @Override
        protected void onCancel(AjaxRequestTarget target, @SuppressWarnings("hiding") Form<?> form) {
            modalWindow.close(target);
        }

        @Override
        protected void onError(AjaxRequestTarget target, @SuppressWarnings("hiding") Form<?> form) {
            feedbackWindow.setContent(feedbackPanel);
            feedbackWindow.show(target);
        }
    });

}

From source file:org.obiba.onyx.quartz.editor.PreviewPanel.java

License:Open Source License

public PreviewPanel(String id, final IModel<T> model, IModel<Questionnaire> questionnaireModel) {
    super(id, model);
    Questionnaire questionnaire = questionnaireModel.getObject();

    QuestionnaireBundle bundle = bundleManager.getBundle(questionnaire.getName());
    bundle.clearMessageSourceCache();/* w  w w.  java2s.com*/
    questionnaire.setQuestionnaireCache(null);

    previewLanguageContainer = new WebMarkupContainer("previewLanguageContainer");
    previewLanguageContainer.setVisible(questionnaire.getLocales().size() > 1);

    final Locale userLocale = Session.get().getLocale();
    IChoiceRenderer<Locale> renderer = new IChoiceRenderer<Locale>() {

        private static final long serialVersionUID = 1L;

        @Override
        public String getIdValue(Locale locale, int index) {
            return locale.toString();
        }

        @Override
        public Object getDisplayValue(Locale locale) {
            return locale.getDisplayLanguage(userLocale);
        }
    };

    final DropDownChoice<Locale> languageChoice = new DropDownChoice<Locale>("languageChoice",
            new Model<Locale>(userLocale), questionnaire.getLocales(), renderer);
    languageChoice.setNullValid(false);
    languageChoice.add(new OnChangeAjaxBehavior() {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            activeQuestionnaireAdministrationService.setDefaultLanguage(languageChoice.getModelObject());
            previewLayout = createPreviewLayout(model);
            PreviewPanel.this.addOrReplace(previewLayout);
            target.addComponent(previewLayout);
        }
    });
    previewLanguageContainer.add(languageChoice);
    add(previewLanguageContainer);

    activeQuestionnaireAdministrationService.setQuestionnaire(questionnaire);
    activeQuestionnaireAdministrationService.setDefaultLanguage(languageChoice.getModelObject());
    activeQuestionnaireAdministrationService.setQuestionnaireDevelopmentMode(true);
}

From source file:org.obiba.onyx.quartz.editor.question.condition.ConditionPanel.java

License:Open Source License

public ConditionPanel(String id, final IModel<Question> questionModel,
        final IModel<Questionnaire> questionnaireModel) {
    super(id);//w  ww .j a v  a2 s  .c o m
    this.questionModel = questionModel;
    this.questionnaireModel = questionnaireModel;

    add(CSSPackageResource.getHeaderContribution(ConditionPanel.class, "ConditionPanel.css"));

    variableWindow = new ModalWindow("variableWindow");
    variableWindow.setCssClassName("onyx");
    variableWindow.setInitialWidth(950);
    variableWindow.setInitialHeight(540);
    variableWindow.setResizable(true);
    variableWindow.setTitle(new ResourceModel("Variable"));
    add(variableWindow);

    add(new MultiLineLabel("explain", new ResourceModel("Explain")));

    Condition condition = new Condition();

    final Question question = questionModel.getObject();

    final Questionnaire questionnaire = questionnaireModel.getObject();
    QuestionnaireFinder questionnaireFinder = QuestionnaireFinder.getInstance(questionnaire);
    questionnaireFinder.buildQuestionnaireCache(); // need a fresh cache

    final IDataSource initialCondition = question.getCondition();
    if (initialCondition != null) {
        if (initialCondition instanceof VariableDataSource) {
            VariableDataSource variableDataSource = (VariableDataSource) initialCondition;
            if (questionnaire.getName().equals(variableDataSource.getTableName())) {
                try {
                    condition.setVariable(questionnaire.getVariable(variableDataSource.getVariableName()));
                    condition.setType(Type.VARIABLE);
                } catch (IllegalArgumentException e) {
                    // not found in this questionnaire
                }
            }
            if (condition.getType() == NONE) { // not found yet
                Variable variable = variableUtils.findVariable(variableDataSource);
                if (variable != null) {
                    try {
                        condition.setVariable(questionnaire.getVariable(variable.getName()));
                        condition.setType(Type.VARIABLE);
                    } catch (IllegalArgumentException e) {
                        // not found
                        Question questionCondition = VariableUtils.findQuestion(variable, questionnaireFinder);
                        condition.setType(Type.QUESTION_CATEGORY);
                        condition.setQuestion(questionCondition);
                        condition.setCategory(VariableUtils.findCategory(variable, questionCondition));
                    }
                }
            }
        } else if (initialCondition instanceof JavascriptDataSource) {
            condition.setType(JAVASCRIPT);
            condition.setScript(((JavascriptDataSource) initialCondition).getScript());
        }
    }

    Model<Condition> model = new Model<Condition>(condition);
    setDefaultModel(model);

    final Form<Void> form = new Form<Void>("form");
    add(form);

    final RadioGroup<Type> conditionType = new RadioGroup<Type>("conditionType",
            new PropertyModel<Type>(model, "type"));
    conditionType.setLabel(new ResourceModel("ConditionType")).setRequired(true);
    form.add(conditionType);

    final Radio<Type> noneType = new Radio<Type>("none", new Model<Type>(NONE));
    noneType.setLabel(new ResourceModel("NoCondition"));
    conditionType.add(noneType).add(new SimpleFormComponentLabel("noneLabel", noneType));

    final Radio<Type> questionType = new Radio<Type>("questionType", new Model<Type>(QUESTION_CATEGORY));
    questionType.setLabel(new ResourceModel("QuestionType"));
    conditionType.add(questionType).add(new SimpleFormComponentLabel("questionTypeLabel", questionType));

    final WebMarkupContainer questionTypeContainer = new WebMarkupContainer("questionTypeContainer");
    questionTypeContainer.setOutputMarkupId(true);
    conditionType.add(questionTypeContainer);

    final WebMarkupContainer questionConditionContainer = new WebMarkupContainer("questionConditionContainer");
    questionConditionContainer.setVisible(condition.getType() == QUESTION_CATEGORY);
    questionTypeContainer.add(questionConditionContainer);

    final List<Question> questions = new ArrayList<Question>(Collections2.filter(
            questionnaire.getQuestionnaireCache().getQuestionCache().values(), new Predicate<Question>() {
                @Override
                public boolean apply(Question q) {
                    return !q.equals(question) && q.getType() != QuestionType.BOILER_PLATE;
                }
            }));
    Collections.sort(questions, new QuestionnaireElementComparator());

    questionName = new DropDownChoice<Question>("question", new PropertyModel<Question>(model, "question"),
            questions, new QuestionnaireElementNameRenderer()) {
        @Override
        public boolean isRequired() {
            return conditionType.getModelObject() == QUESTION_CATEGORY;
        }
    };

    questionName.setLabel(new ResourceModel("Question"));
    questionName.setNullValid(false);
    questionConditionContainer.add(questionName)
            .add(new SimpleFormComponentLabel("questionLabel", questionName));

    final List<Category> categories = findCategories();
    final DropDownChoice<Category> categoryName = new DropDownChoice<Category>("category",
            new PropertyModel<Category>(model, "category"), categories,
            new QuestionnaireElementNameRenderer()) {
        @Override
        public boolean isRequired() {
            return conditionType.getModelObject() == QUESTION_CATEGORY;
        }
    };
    categoryName.setLabel(new ResourceModel("Category"));
    categoryName.setNullValid(false);
    questionConditionContainer.add(categoryName)
            .add(new SimpleFormComponentLabel("categoryLabel", categoryName));

    questionName.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            categories.clear();
            categories.addAll(findCategories());
            target.addComponent(categoryName);
        }
    });

    Radio<Type> variableType = new Radio<Type>("variableType", new Model<Type>(VARIABLE));
    variableType.setLabel(new ResourceModel("VariableType"));
    conditionType.add(variableType).add(new SimpleFormComponentLabel("variableTypeLabel", variableType));

    final WebMarkupContainer variableTypeContainer = new WebMarkupContainer("variableTypeContainer");
    variableTypeContainer.setOutputMarkupId(true);
    conditionType.add(variableTypeContainer);

    final WebMarkupContainer variableContainer = new WebMarkupContainer("variableContainer");
    variableContainer.setVisible(condition.getType() == VARIABLE);
    variableTypeContainer.add(variableContainer);

    final List<Variable> variables = new ArrayList<Variable>(
            Collections2.filter(questionnaire.getVariables(), new Predicate<Variable>() {
                @Override
                public boolean apply(Variable v) {
                    return v.getValueType().equals(BooleanType.get());
                }
            }));

    final DropDownChoice<Variable> variableDropDown = new DropDownChoice<Variable>("variable",
            new PropertyModel<Variable>(model, "variable"), variables, new VariableRenderer()) {
        @Override
        public boolean isRequired() {
            return conditionType.getModelObject() == VARIABLE;
        }
    };
    variableDropDown.setLabel(new ResourceModel("Variable")).setOutputMarkupId(true);
    variableContainer.add(variableDropDown);

    final WebMarkupContainer previewVariableVisibility = new WebMarkupContainer("previewVariableVisibility");
    variableContainer.add(previewVariableVisibility.setOutputMarkupId(true));

    final Image previewVariable = new Image("previewVariable", Images.ZOOM);
    previewVariable.add(new AttributeModifier("title", true, new ResourceModel("Preview")));
    previewVariable.setVisible(variableDropDown.getModelObject() != null);
    previewVariableVisibility.add(previewVariable);

    final Label previewScript = new Label("previewScript", variableDropDown.getModelObject() == null ? ""
            : variableDropDown.getModelObject().getAttributeStringValue("script"));
    previewScript.add(new SyntaxHighlighterBehavior());
    previewScript.add(new AttributeAppender("style", true, new Model<String>("display: none;"), " "));
    previewVariableVisibility.add(previewScript);

    final Map<String, Object> tooltipCfg = new HashMap<String, Object>();
    tooltipCfg.put("delay", 100);
    tooltipCfg.put("showURL", false);
    tooltipCfg.put("top", -30);
    tooltipCfg.put("bodyHandler",
            "function() { return $(\"#" + previewScript.getMarkupId(true) + "\").html(); }");
    previewVariable.add(new TooltipBehavior(null, tooltipCfg));

    variableContainer.add(new AjaxLink<Void>("newVariable") {
        @Override
        public void onClick(AjaxRequestTarget target) {

            @SuppressWarnings({ "rawtypes", "unchecked" })
            VariablePanel variablePanel = new VariablePanel("content", new Model(null), questionnaireModel,
                    BooleanType.get()) {
                @Override
                public void onSave(@SuppressWarnings("hiding") AjaxRequestTarget target,
                        Variable createdVariable) {
                    variables.add(createdVariable);
                    questionnaire.addVariable(createdVariable);
                    variableDropDown.setModelObject(createdVariable);
                    previewVariable.setVisible(true);
                    previewScript.setDefaultModelObject(createdVariable.getAttributeStringValue("script"));
                    variableWindow.close(target);
                    target.addComponent(variableDropDown);
                    target.addComponent(previewVariableVisibility);
                }

                @Override
                public void onCancel(@SuppressWarnings("hiding") AjaxRequestTarget target) {
                    variableWindow.close(target);
                }
            };

            variableWindow.setContent(variablePanel);
            variableWindow.show(target);
        }
    }.add(new Image("newVariableImg", Images.ADD))
            .add(new AttributeModifier("title", true, new ResourceModel("NewVariable"))));

    variableDropDown.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            Variable variable = variableDropDown.getModelObject();
            previewVariable.setVisible(variable != null);
            previewScript.setDefaultModelObject(
                    variable == null ? null : variable.getAttributeStringValue("script"));
            target.addComponent(previewVariableVisibility);
        }
    });

    Radio<Type> javascriptType = new Radio<Type>("javascriptType", new Model<Type>(JAVASCRIPT));
    javascriptType.setLabel(new ResourceModel("JavascriptType"));
    conditionType.add(javascriptType).add(new SimpleFormComponentLabel("javascriptTypeLabel", javascriptType));

    final TextArea<String> javascriptField = new TextArea<String>("javascriptField",
            new PropertyModel<String>(condition, "script"));
    javascriptField.setOutputMarkupPlaceholderTag(true);
    javascriptField.setVisible(condition.getType() == JAVASCRIPT);
    conditionType.add(javascriptField);

    javascriptField.add(new IValidator<String>() {

        @Override
        public void validate(final IValidatable<String> validatable) {
            JavascriptUtils.compile(validatable.getValue(), question.getName(), ConditionPanel.this, form);
        }
    });

    conditionType.add(new AjaxFormChoiceComponentUpdatingBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            Type type = conditionType.getModelObject();
            switch (type) {
            case NONE:
                questionName.setModelObject(null);
                categoryName.setModelObject(null);
                variableDropDown.setModelObject(null);
                javascriptField.setModelObject(null);
                break;
            case QUESTION_CATEGORY:
                variableDropDown.setModelObject(null);
                javascriptField.setModelObject(null);
                break;
            case VARIABLE:
                questionName.setModelObject(null);
                categoryName.setModelObject(null);
                javascriptField.setModelObject(null);
                break;
            case JAVASCRIPT:
                questionName.setModelObject(null);
                categoryName.setModelObject(null);
                variableDropDown.setModelObject(null);
                break;
            }
            questionConditionContainer.setVisible(type == QUESTION_CATEGORY);
            variableContainer.setVisible(type == VARIABLE);
            javascriptField.setVisible(type == JAVASCRIPT);
            target.addComponent(questionTypeContainer);
            target.addComponent(variableTypeContainer);
            target.addComponent(javascriptField);
        }
    });

}

From source file:org.obiba.onyx.quartz.editor.variable.VariablePanel.java

License:Open Source License

public VariablePanel(String id, final IModel<Variable> variableModel,
        final IModel<Questionnaire> questionnaireModel, ValueType forcedValueType) {
    super(id);//from   w ww  .j  a va2s .  co m

    add(CSSPackageResource.getHeaderContribution(VariablePanel.class, "VariablePanel.css"));

    final EditedVariable editedVariable = new EditedVariable();
    final Variable variable = variableModel.getObject();
    if (variable == null) {
        editedVariable.setValueType(forcedValueType);
        editedVariable.setRepeatable(false);
    } else {
        editedVariable.setName(variable.getName());
        editedVariable.setValueType(variable.getValueType());
        editedVariable.setRepeatable(variable.isRepeatable());
        editedVariable.setScript(variable.getAttributeStringValue("script"));
    }
    final IModel<EditedVariable> model = new Model<EditedVariable>(editedVariable);
    setDefaultModel(model);

    feedbackPanel = new FeedbackPanel("content");
    feedbackWindow = new FeedbackWindow("feedback");
    feedbackWindow.setOutputMarkupId(true);

    add(feedbackWindow);

    add(form = new Form<EditedVariable>("form", model));

    final TextField<String> name = new TextField<String>("name",
            new PropertyModel<String>(form.getModel(), "name"));
    name.setLabel(new ResourceModel("Name"));
    name.add(new RequiredFormFieldBehavior());
    name.add(new PatternValidator(Pattern.compile("[a-zA-Z0-9_\\-\\.]+")));
    name.add(new AbstractValidator<String>() {
        @Override
        protected void onValidate(IValidatable<String> validatable) {
            if (!StringUtils.equals(model.getObject().getName(), validatable.getValue())) {
                try {
                    if (questionnaireModel.getObject().getVariable(validatable.getValue()) != null) {
                        error(validatable, "VariableAlreadyExists");
                    }
                } catch (Exception e) {
                    // do nothing, variable was not found
                }
            }
        }
    });
    form.add(name).add(new SimpleFormComponentLabel("nameLabel", name))
            .add(new HelpTooltipPanel("nameHelp", new ResourceModel("Name.Tooltip")));

    List<ValueType> types = new ArrayList<ValueType>();
    types.add(IntegerType.get());
    types.add(DecimalType.get());
    types.add(BooleanType.get());
    types.add(DateType.get());
    types.add(DateTimeType.get());
    types.add(TextType.get());
    types.add(LocaleType.get());
    types.add(BinaryType.get());

    DropDownChoice<ValueType> valueType = new DropDownChoice<ValueType>("type",
            new PropertyModel<ValueType>(form.getModel(), "valueType"), types, new ValueTypeRenderer());
    valueType.add(new RequiredFormFieldBehavior());

    QuestionnaireFinder questionnaireFinder = QuestionnaireFinder.getInstance(questionnaireModel.getObject());
    questionnaireFinder.buildQuestionnaireCache();
    boolean usedInQuestion = variableValidationUtils.findUsedInQuestion(variable,
            questionnaireModel.getObject().getQuestionnaireCache()) == null;
    valueType.setEnabled((forcedValueType == null) ? usedInQuestion : false);

    form.add(valueType.setLabel(new ResourceModel("Type")))
            .add(new SimpleFormComponentLabel("typeLabel", valueType));

    CheckBox repeatable = new CheckBox("repeatable", new PropertyModel<Boolean>(form.getModel(), "repeatable"));

    form.add(repeatable.setLabel(new ResourceModel("Repeatable")))
            .add(new SimpleFormComponentLabel("repeatableLabel", repeatable));

    TextArea<String> script = new TextArea<String>("script",
            new PropertyModel<String>(form.getModel(), "script"));
    script.add(new RequiredFormFieldBehavior());
    script.add(new IValidator<String>() {

        @Override
        public void validate(final IValidatable<String> validatable) {
            JavascriptUtils.compile(validatable.getValue(), name.getConvertedInput(), VariablePanel.this, form);
        }
    });

    form.add(script.setLabel(new ResourceModel("Script")))
            .add(new SimpleFormComponentLabel("scriptLabel", script))
            .add(new HelpTooltipPanel("scriptHelp", new ResourceModel("Script.Tooltip")));

    Set<ValueTable> valueTables = magmaInstanceProvider.getOnyxDatasource().getValueTables();
    List<String> tables = new ArrayList<String>(valueTables.size());
    for (ValueTable valueTable : valueTables) {
        if (valueTable.isForEntityType(MagmaInstanceProvider.PARTICIPANT_ENTITY_TYPE)) {
            tables.add(valueTable.getName());
        }
    }
    Collections.sort(tables);

    final DropDownChoice<String> tablesDropDown = new DropDownChoice<String>("tables",
            new Model<String>(tables.get(0)), tables);
    tablesDropDown.setNullValid(false);
    form.add(tablesDropDown.setLabel(new ResourceModel("Tables")))
            .add(new SimpleFormComponentLabel("tablesLabel", tablesDropDown));

    final List<String> tableVariables = new ArrayList<String>();
    findTableVariables(tablesDropDown, tableVariables);
    final DropDownChoice<String> tableVariablesDropDown = new DropDownChoice<String>("variables",
            new Model<String>(tableVariables.get(0)), tableVariables);
    tableVariablesDropDown.setNullValid(false).setOutputMarkupId(true);
    form.add(tableVariablesDropDown.setLabel(new ResourceModel("Variables")))
            .add(new SimpleFormComponentLabel("variablesLabel", tableVariablesDropDown));

    final TextField<String> selectedVariable = new TextField<String>("selectedVariable",
            new Model<String>(tableVariables.isEmpty() ? ""
                    : tablesDropDown.getModelObject() + ":" + tableVariablesDropDown.getModelObject()));
    form.add(selectedVariable.setOutputMarkupId(true));

    tablesDropDown.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            findTableVariables(tablesDropDown, tableVariables);
            tableVariablesDropDown.setModelObject(tableVariables.isEmpty() ? null : tableVariables.get(0));
            selectedVariable.setDefaultModelObject(tableVariables.isEmpty() ? ""
                    : tablesDropDown.getModelObject() + ":" + tableVariablesDropDown.getModelObject());
            target.addComponent(tableVariablesDropDown);
            target.addComponent(selectedVariable);
        }
    });
    tableVariablesDropDown.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            selectedVariable.setDefaultModelObject(
                    tablesDropDown.getModelObject() + ":" + tableVariablesDropDown.getModelObject());
            target.addComponent(selectedVariable);
        }
    });

    form.add(new SaveCancelPanel("saveCancel", form) {
        @Override
        protected void onSave(AjaxRequestTarget target, Form<?> form1) {
            Builder builder = Variable.Builder.newVariable(editedVariable.getName(),
                    editedVariable.getValueType(), "Participant");
            builder.addAttribute("script", editedVariable.getScript());

            if (editedVariable.isRepeatable())
                builder.repeatable();

            VariablePanel.this.onSave(target, builder.build());
        }

        @Override
        protected void onCancel(AjaxRequestTarget target, @SuppressWarnings("hiding") Form<?> form) {
            VariablePanel.this.onCancel(target);
        }

        @Override
        protected void onError(AjaxRequestTarget target, @SuppressWarnings("hiding") Form<?> form) {
            feedbackWindow.setContent(feedbackPanel);
            feedbackWindow.show(target);
        }
    });

}

From source file:org.obiba.onyx.wicket.contraindication.ObservedContraIndicationPanel.java

License:Open Source License

@SuppressWarnings("serial")
public ObservedContraIndicationPanel(String id, IModel<IContraindicatable> contraindicatable) {
    super(id, contraindicatable);
    setOutputMarkupId(true);//from   ww w  . j  a  v a2  s .  c  o m

    final RadioGroup radioGroup = new RadioGroup("radioGroup", new PropertyModel(this, "selectedRadio"));
    radioGroup.setLabel(new StringResourceModel("ContraIndication", this, null));
    radioGroup.add(new AjaxFormChoiceComponentUpdatingBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            log.info("radioGroup.onUpdate={}", selectedRadio);
            if (selectedRadio.equals(NO)) {
                log.info("invalidating models");
                contraIndicationDropDownChoice.setModelObject(null);
                otherContraIndication.setModelObject(null);
            }
            target.addComponent(ObservedContraIndicationPanel.this);
            target.appendJavascript("Resizer.resizeWizard();");
        }
    });
    add(radioGroup);
    ListView radioList = new ListView("radioItem", Arrays.asList(new String[] { YES, NO })) {

        @Override
        protected void populateItem(final ListItem item) {
            Radio radio = new Radio("radio", item.getModel());
            radio.setLabel(new StringResourceModel((String) item.getModelObject(),
                    ObservedContraIndicationPanel.this, null));
            item.add(radio);
            item.add(new SimpleFormComponentLabel("radioLabel", radio));
        }

    }.setReuseItems(true);
    radioGroup.add(radioList);
    radioGroup.setRequired(true);

    contraIndicationDropDownChoice = new DropDownChoice("ciChoice",
            new PropertyModel(getDefaultModel(), "contraindication"),
            getContraindicatable().getContraindications(Contraindication.Type.OBSERVED),
            new ContraindicationChoiceRenderer()) {

        @Override
        public boolean isEnabled() {
            // return selectedRadio == null || selectedRadio.equals(YES);
            return (selectedRadio == null) ? false : selectedRadio.equals(YES);
        }

        @Override
        public boolean isRequired() {
            return isEnabled();
        }
    };
    contraIndicationDropDownChoice.setOutputMarkupId(true);
    contraIndicationDropDownChoice.setLabel(new StringResourceModel("ContraIndicationSelection", this, null));

    // Use an OnChangeAjaxBehavior so that the form submission happens, but only for this component
    // This allows us to have the model set to the proper value
    contraIndicationDropDownChoice.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            log.debug("contraIndicationDropDownChoice.onUpdate() selectedRadio={} selectedCi={}", selectedRadio,
                    getContraindicatable().getContraindication());
            // make sure the right radio is selected
            // use setModelObject in order to let the RadioGroup component be aware of the change.
            radioGroup.setModelObject(getContraindicatable().isContraindicated() ? YES : NO);

            // Invalidate the reason.
            otherContraIndication.setModelObject(null);
            target.addComponent(ObservedContraIndicationPanel.this);
            target.appendJavascript("Resizer.resizeWizard();");
        }

    });
    add(contraIndicationDropDownChoice);

    otherContraIndication = new TextArea("otherCi",
            new PropertyModel(getDefaultModel(), "otherContraindication")) {

        @Override
        public boolean isVisible() {
            // The text area and its associated label should only be displayed when the selected contraindication requires a
            // description. The label's visibility is bound to the text area visibility using a <wicket:enclosure> tag in
            // the markup.
            Contraindication selectedCi = (Contraindication) contraIndicationDropDownChoice.getModelObject();
            return contraIndicationDropDownChoice.isEnabled() && selectedCi != null
                    && selectedCi.getRequiresDescription();
        }

        @Override
        public boolean isRequired() {
            return isVisible();
        }

    };
    otherContraIndication.setOutputMarkupId(true);
    otherContraIndication.setLabel(new StringResourceModel("OtherContraIndication", this, null));
    otherContraIndication.add(new StringValidator.MaximumLengthValidator(2000));
    add(otherContraIndication);

    FormComponentLabel otherContraIndicationLabel = new FormComponentLabel("otherLabel", otherContraIndication);
    add(otherContraIndicationLabel);
}