Example usage for org.apache.wicket Component setEnabled

List of usage examples for org.apache.wicket Component setEnabled

Introduction

In this page you can find the example usage for org.apache.wicket Component setEnabled.

Prototype

public final Component setEnabled(final boolean enabled) 

Source Link

Document

Sets whether this component is enabled.

Usage

From source file:org.geoserver.web.wicket.PointPanel.java

License:Open Source License

public PointPanel setReadOnly(final boolean readOnly) {
    visitChildren(TextField.class, new org.apache.wicket.Component.IVisitor() {
        public Object component(Component component) {
            component.setEnabled(!readOnly);
            return null;
        }/*w ww.  j  ava 2s.c  om*/
    });

    return this;
}

From source file:org.geoserver.wms.eo.web.EoLayerGroupEditPage.java

License:Open Source License

public EoLayerGroupEditPage(PageParameters parameters) {
    String groupName = parameters.getString(GROUP);
    String wsName = parameters.getString(WORKSPACE);

    LayerGroupInfo lg = wsName != null ? getCatalog().getLayerGroupByName(wsName, groupName)
            : getCatalog().getLayerGroupByName(groupName);

    if (lg == null) {
        error(new ParamResourceModel("LayerGroupEditPage.notFound", this, groupName).getString());
        doReturn(LayerGroupPage.class);
        return;/*from   w w  w . j  a  va 2s.c o m*/
    }

    initUI(lg);

    if (!isAuthenticatedAsAdmin()) {
        Form f = (Form) get("form");

        //global layer groups only editable by full admin
        if (lg.getWorkspace() == null) {
            //disable all form components but cancel
            f.visitChildren(new IVisitor<Component>() {
                @Override
                public Object component(Component c) {
                    if (!(c instanceof AbstractLink && "cancel".equals(c.getId()))) {
                        c.setEnabled(false);
                    }
                    return CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER;
                }
            });
            f.get("save").setVisible(false);

            info(new StringResourceModel("globalLayerGroupReadOnly", this, null).getString());
        }

        //always disable the workspace toggle
        f.get("workspace").setEnabled(false);
    }
}

From source file:org.geoserver.wps.web.RangePanel.java

License:Open Source License

public RangePanel setReadOnly(final boolean readOnly) {
    visitChildren(TextField.class, new org.apache.wicket.Component.IVisitor() {
        public Object component(Component component) {
            component.setEnabled(!readOnly);
            return null;
        }//w w  w  .j  a v a  2  s.c  o  m
    });
    return this;
}

From source file:org.obiba.onyx.ruby.core.wicket.wizard.AskedContraIndicationStep.java

License:Open Source License

@Override
public void handleWizardState(WizardForm form, AjaxRequestTarget target) {
    super.handleWizardState(form, target);

    // Disable interrupt link.
    Component interruptLink = ((RubyWizardForm) form).getInterruptLink();
    interruptLink.setEnabled(false);

    if (target != null) {
        target.addComponent(interruptLink);
    }//w  w  w.  j a v a 2s.c o m
}

From source file:org.opensingular.form.wicket.behavior.ConfigureByMInstanciaAttributesBehavior.java

License:Apache License

@Override
public void onConfigure(Component component) {
    super.onConfigure(component);
    if (component != null) {
        component.setEnabled(isInstanceEnabled(component));
        component.setVisible(isInstanceVisible(component));
    }//from w w  w.j a  va  2  s .  co  m
}

From source file:org.opensingular.lib.wicket.util.util.IBehaviorsMixin.java

License:Apache License

default Behavior enabledIf(IModel<Boolean> model) {
    return new Behavior() {
        @Override/*from  ww w .j av a  2 s .c om*/
        public void onConfigure(Component component) {
            component.setEnabled(model.getObject());
        }
    };
}

From source file:org.patientview.radar.web.pages.patient.srns.SrnsPatientPageReadOnly.java

License:Open Source License

public SrnsPatientPageReadOnly(PageParameters parameters) {
    super(parameters);

    //a patient cannot edit so hide and disable stuff so only a read only view is available
    visitChildren(new IVisitor<Component, Object>() {
        public void component(Component component, IVisit<Object> objectIVisit) {
            RadarSecuredSession session = RadarSecuredSession.get();
            if (session.get().isSignedIn()) {
                if (session.getRoles().hasRole(User.ROLE_PATIENT)) {
                    if (component instanceof FormComponent) {
                        component.setEnabled(false);
                    }/* www  . j  a  v a  2  s  . c o  m*/

                    if (component instanceof AjaxSubmitLink) {
                        component.setVisible(false);
                    }

                    for (String regexToHide : Arrays.asList("\\w*edit\\w*(container|form)",
                            "\\w*delete\\w*(container|form)", "\\w*add\\w*(container|form)",
                            "\\w*addnew\\w*")) {
                        Matcher matcher = Pattern.compile(regexToHide, Pattern.CASE_INSENSITIVE)
                                .matcher(component.getId().toLowerCase());
                        if (matcher.matches()) {
                            component.setVisible(false);
                        }
                    }

                    for (String regexToEnable : Arrays.asList("\\w*switcher\\w*")) {
                        Matcher matcher = Pattern.compile(regexToEnable, Pattern.CASE_INSENSITIVE)
                                .matcher(component.getId().toLowerCase());
                        if (matcher.matches()) {
                            component.setEnabled(true);
                        }
                    }
                }
            }

        }
    });
}

From source file:org.patientview.radar.web.panels.DemographicsPanel.java

License:Open Source License

public DemographicsPanel(String id, final IModel<Patient> patientModel, final PatientCallBack patientCallBack) {

    super(id);//from   www . j a va2  s .  c o m

    List<Component> nonEditableComponents = new ArrayList<Component>();

    setOutputMarkupId(true);
    setOutputMarkupPlaceholderTag(true);

    final User user = RadarSecuredSession.get().getUser();

    // Set up model - if given radar number loadable detachable getting demographics by radar number
    final CompoundPropertyModel<Patient> model = new CompoundPropertyModel<Patient>(patientModel.getObject());
    final IModel<Date> registrationHeaderModel = new Model<Date>();

    if (patientModel.getObject().getDateReg() != null) {
        registrationHeaderModel.setObject(patientModel.getObject().getDateReg());
    } else {
        registrationHeaderModel.setObject(new Date());
    }

    final IModel<Long> radarHeaderModel = new Model<Long>(patientModel.getObject().getRadarNo());
    final IModel<String> forenameHeaderModel = new Model<String>(patientModel.getObject().getForename());
    final IModel<String> surnameHeaderModel = new Model<String>(patientModel.getObject().getSurname());
    final IModel<Date> dobHeaderModel = new Model<Date>(patientModel.getObject().getDob());

    // Set up form
    final Form<Patient> form = new Form<Patient>("form", model) {
        @Override
        protected void onSubmit() {

            Patient patient = getModelObject();
            patient.setRadarConsentConfirmedByUserId(user.getUserId());

            try {

                patientModel.setObject(patient);
                patientModel.getObject().setDateReg(new Date());

                userManager.addPatientUserOrUpdatePatient(patient);

                patientCallBack.updateModel(patient.getRadarNo());
                // Update the header with the saved record

                forenameHeaderModel.setObject(patientModel.getObject().getForename());
                surnameHeaderModel.setObject(patientModel.getObject().getSurname());
                dobHeaderModel.setObject(patientModel.getObject().getDob());
                registrationHeaderModel.setObject(patientModel.getObject().getDateReg());
                radarHeaderModel.setObject(patient.getRadarNo());

            } catch (RegisterException re) {
                LOGGER.error("Registration Exception {} ", re.getMessage());
                error("Could not register patient" + re.getMessage());
            } catch (Exception e) {
                String message = "Error registering new patient to accompany this demographic";
                LOGGER.error("{}, message {}", message, e.getMessage());
                error(message);
            }

            // create new diagnosis if it doesnt exist becuase diagnosis code is set in demographics tab
            if (patient.hasValidId()) {
                Diagnosis diagnosis = diagnosisManager.getDiagnosisByRadarNumber(patient.getRadarNo());
                if (diagnosis == null) {
                    Diagnosis diagnosisNew = new Diagnosis();
                    diagnosisNew.setRadarNumber(patient.getRadarNo());
                    DiagnosisCode diagnosisCode = (DiagnosisCode) ((DropDownChoice) get("diagnosis"))
                            .getModelObject();
                    diagnosisNew.setDiagnosisCode(diagnosisCode);
                    diagnosisManager.saveDiagnosis(diagnosisNew);
                }
            }

        }
    };

    // More info
    Label nhsNumber = new Label("nhsno");
    WebMarkupContainer nhsNumberContainer = new WebMarkupContainer("nhsNumberContainer");
    nhsNumberContainer.add(nhsNumber);

    Label chiNumber = new Label("chiNumber");
    WebMarkupContainer chiNumberContainer = new WebMarkupContainer("chiNumberContainer") {
        @Override
        public boolean isVisible() {
            return false;
        }
    };
    chiNumberContainer.add(chiNumber);

    form.add(nhsNumberContainer, chiNumberContainer);

    form.setOutputMarkupId(true);
    form.setOutputMarkupPlaceholderTag(true);

    add(form);

    final List<Component> componentsToUpdateList = new ArrayList<Component>();

    form.add(new Label("addNewPatientLabel", "Add a New Patient") {
        @Override
        public boolean isVisible() {
            return patientModel.getObject().hasValidId();
        }
    });

    final TextField radarNumberField = new TextField("radarNo", radarHeaderModel);
    radarNumberField.setEnabled(false);
    radarNumberField.setOutputMarkupId(true);
    radarNumberField.setOutputMarkupPlaceholderTag(true);

    form.add(radarNumberField);
    componentsToUpdateList.add(radarNumberField);

    final TextField dateRegistered = new org.apache.wicket.extensions.markup.html.form.DateTextField("dateReg",
            registrationHeaderModel, CommonUtils.UK_DATE_FORMAT);

    dateRegistered.setOutputMarkupId(true);
    dateRegistered.setOutputMarkupPlaceholderTag(true);

    form.add(dateRegistered);
    componentsToUpdateList.add(dateRegistered);

    RadarRequiredDropdownChoice diagnosis = new RadarRequiredDropdownChoice("diagnosis",
            RadarModelFactory.getDiagnosisCodeModel(new Model<Long>(patientModel.getObject().getRadarNo()),
                    diagnosisManager),
            diagnosisManager.getDiagnosisCodes(), new ChoiceRenderer("abbreviation", "id"), form,
            componentsToUpdateList) {
        @Override
        public boolean isEnabled() {
            RadarSecuredSession securedSession = RadarSecuredSession.get();
            if (securedSession.getRoles().hasRole(User.ROLE_PATIENT)) {
                return false;
            }
            return getModelObject() == null;
        }
    };

    String diseaseGroup = patientModel.getObject().getDiseaseGroup().getId();
    DiagnosisCode diagnosisCode = new DiagnosisCode();

    // WARNING - This doesn't make sense, you cannot equate a disease group with a diagnosis code,
    // but works because these groups do not have specific diagnosis
    if (diseaseGroup.equals(DiseaseGroup.SRNS_DISEASE_GROUP_ID)) {
        diagnosisCode.setId(DiagnosisCode.SRNS_ID);
    } else if (diseaseGroup.equals(DiseaseGroup.MPGN_DISEASEGROUP_ID)) {
        diagnosisCode.setId(DiagnosisCode.MPGN_ID);
    }

    diagnosis.setModel(new Model(diagnosisCode));

    /**
     * Basic fields
     */
    RadarRequiredTextField surname = new RadarRequiredTextField("surname", form, componentsToUpdateList);
    RadarRequiredTextField forename = new RadarRequiredTextField("forename", form, componentsToUpdateList);
    RadarRequiredDateTextField dateOfBirth = new RadarRequiredDateTextField("dob", form,
            componentsToUpdateList);

    dateOfBirth.setRequired(true);

    form.add(diagnosis, surname, forename, dateOfBirth);
    nonEditableComponents.add(surname);
    nonEditableComponents.add(forename);
    nonEditableComponents.add(dateOfBirth);
    /**
     *  Add basic fields for header too... apparently we can't render same component twice in wicket!..
     *
     *  As we cant set demographicsModelObject as final outside isVisible() implementations there's a bunch of
     *      code duplication
     */

    // forename

    final Label nameLabel = new Label("nameLabel", "Name") {
        @Override
        public boolean isVisible() {
            return StringUtils.isNotBlank(patientModel.getObject().getForename());
        }
    };
    nameLabel.setOutputMarkupId(true);
    nameLabel.setOutputMarkupPlaceholderTag(true);
    form.add(nameLabel);

    final TextField forenameForHeader = new TextField("forenameForHeader", forenameHeaderModel) {
        @Override
        public boolean isVisible() {
            return StringUtils.isNotBlank(patientModel.getObject().getForename());
        }
    };
    forenameForHeader.setOutputMarkupId(true);
    forenameForHeader.setOutputMarkupPlaceholderTag(true);
    componentsToUpdateList.add(forenameForHeader);
    componentsToUpdateList.add(nameLabel);

    // surname
    final TextField surnameForHeader = new TextField("surnameForHeader", surnameHeaderModel) {
        @Override
        public boolean isVisible() {

            return StringUtils.isNotBlank(patientModel.getObject().getSurname());
        }
    };
    surnameForHeader.setOutputMarkupId(true);
    surnameForHeader.setOutputMarkupPlaceholderTag(true);
    componentsToUpdateList.add(surnameForHeader);

    // date of birth
    final Label dobLabel = new Label("dobLabel", "DoB") {
        @Override
        public boolean isVisible() {
            return patientModel.getObject().getDob() != null;
        }
    };
    dobLabel.setOutputMarkupId(true);
    dobLabel.setOutputMarkupPlaceholderTag(true);
    form.add(dobLabel);

    final TextField dateOfBirthForHeader = new org.apache.wicket.extensions.markup.html.form.DateTextField(
            "dateOfBirthForHeader", dobHeaderModel, CommonUtils.UK_DATE_FORMAT) {
        @Override
        public boolean isVisible() {
            return patientModel.getObject().getDob() != null;
        }
    };
    dateOfBirthForHeader.setOutputMarkupId(true);
    dateOfBirthForHeader.setOutputMarkupPlaceholderTag(true);
    componentsToUpdateList.add(dateOfBirthForHeader);
    componentsToUpdateList.add(dobLabel);

    form.add(diagnosis, surnameForHeader, forenameForHeader, dateOfBirthForHeader);

    // Sex
    RadarRequiredDropdownChoice sex = new RadarRequiredDropdownChoice("sexModel",
            demographicsManager.getSexes(), new ChoiceRenderer<Sex>("type", "id"), form,
            componentsToUpdateList);

    // Ethnicity
    DropDownChoice<Ethnicity> ethnicity = new DropDownChoice<Ethnicity>("ethnicity",
            utilityManager.getEthnicities(), new ChoiceRenderer<Ethnicity>("name", "id"));
    form.add(sex, ethnicity);

    // Address fields
    TextField address1 = new TextField("address1");
    TextField address2 = new TextField("address2");
    TextField address3 = new TextField("address3");
    TextField address4 = new TextField("address4");
    RadarTextFieldWithValidation postcode = new RadarTextFieldWithValidation("postcode",
            new PatternValidator("[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$"), form,
            componentsToUpdateList);

    form.add(address1, address2, address3, address4, postcode);
    nonEditableComponents.add(address1);
    nonEditableComponents.add(address2);
    nonEditableComponents.add(address3);
    nonEditableComponents.add(address4);
    nonEditableComponents.add(postcode);

    // Archive fields
    TextField surnameAlias = new TextField("surnameAlias");
    TextField previousPostcode = new TextField("postcodeOld");
    form.add(surnameAlias, previousPostcode);

    // More info
    RadarRequiredTextField hospitalNumber = new RadarRequiredTextField("hospitalnumber", form,
            componentsToUpdateList);
    TextField renalRegistryNumber = new TextField("rrNo");
    TextField ukTransplantNumber = new TextField("uktNo");

    form.add(hospitalNumber, renalRegistryNumber, ukTransplantNumber);
    nonEditableComponents.add(hospitalNumber);
    // Status, consultants and centres drop down boxes
    form.add(new DropDownChoice<Status>("statusModel", demographicsManager.getStatuses(),
            new ChoiceRenderer<Status>("abbreviation", "id")));

    // Consultant and renal unit
    Label sourceUnitCodeLabel = new Label("sourceUnitCodeLabel", "Linked to") {
        @Override
        public boolean isVisible() {
            return model.getObject().isLinked();

        }
    };

    String sourceUnitNameLabelValue = model.getObject().getPatientLinkUnitCode() != null
            ? utilityManager.getCentre(model.getObject().getPatientLinkUnitCode()).getName()
            : "";

    Label sourceUnitCode = new Label("sourceUnitCode", sourceUnitNameLabelValue) {
        @Override
        public boolean isVisible() {
            return model.getObject().isLinked();

        }
    };
    form.add(sourceUnitCodeLabel, sourceUnitCode);

    final ClinicianDropDown clinician = new ClinicianDropDown("clinician", user, form.getModelObject());
    form.add(clinician);

    DropDownChoice<Centre> renalUnit = new PatientCentreDropDown("renalUnit", user, form.getModelObject(), form,
            componentsToUpdateList);

    renalUnit.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            Patient patient = model.getObject();
            if (patient != null) {
                clinician.updateCentre(
                        patient.getRenalUnit() != null ? patient.getRenalUnit().getUnitCode() : null);
            }

            clinician.clearInput();
            target.add(clinician);
        }
    });

    form.add(renalUnit);

    final IModel<String> consentUserModel = new Model<String>(
            utilityManager.getUserName(patientModel.getObject().getRadarConsentConfirmedByUserId()));

    form.add(new ExternalLink("consentFormsLink", "http://www.rarerenal.org/join/criteria-and-consent/"));

    final Label tickConsentUser = new Label("radarConsentConfirmedByUserId", consentUserModel) {
        @Override
        public boolean isVisible() {
            return StringUtils.isNotEmpty(consentUserModel.getObject());
        }
    };
    tickConsentUser.setOutputMarkupId(true);
    tickConsentUser.setOutputMarkupPlaceholderTag(true);
    form.add(tickConsentUser);

    final RadarRequiredCheckBox consent = new RadarRequiredCheckBox("consent", form, componentsToUpdateList);

    consent.add(new AjaxFormComponentUpdatingBehavior("onclick") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {

            target.add(tickConsentUser);

            if (consent.getModel().getObject().equals(Boolean.TRUE)) {
                model.getObject()
                        .setRadarConsentConfirmedByUserId(RadarSecuredSession.get().getUser().getUserId());
                consentUserModel.setObject(RadarSecuredSession.get().getUser().getName());
                tickConsentUser.setVisible(true);

            } else {
                tickConsentUser.setVisible(false);
            }
        }
    });

    form.add(consent);

    final Label successMessageTop = RadarComponentFactory.getSuccessMessageLabel("successMessageTop", form,
            componentsToUpdateList);
    final Label successMessageBottom = RadarComponentFactory.getSuccessMessageLabel("successMessageBottom",
            form, componentsToUpdateList);

    Label errorMessage = RadarComponentFactory.getErrorMessageLabel("errorMessage", form,
            componentsToUpdateList);

    AjaxSubmitLink ajaxSubmitLinkTop = new AjaxSubmitLink("saveTop") {

        @Override
        protected void onSubmit(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
            ajaxRequestTarget.add(componentsToUpdateList.toArray(new Component[componentsToUpdateList.size()]));
            successMessageTop.setVisible(true);
            successMessageBottom.setVisible(true);
            ajaxRequestTarget.add(successMessageTop);
            ajaxRequestTarget.add(successMessageBottom);
            ajaxRequestTarget.appendJavaScript(RadarApplication.FORM_IS_DIRTY_FALSE_SCRIPT);
        }

        @Override
        protected void onError(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
            ajaxRequestTarget.add(componentsToUpdateList.toArray(new Component[componentsToUpdateList.size()]));
            successMessageTop.setVisible(false);
            successMessageBottom.setVisible(false);
            ajaxRequestTarget.add(successMessageTop);
            ajaxRequestTarget.add(successMessageBottom);
        }
    };

    ajaxSubmitLinkTop.add(new AttributeModifier("value", new AbstractReadOnlyModel() {
        @Override
        public Object getObject() {
            return patientModel.getObject() == null ? "Add this patient" : "Update";
        }
    }));

    form.add(ajaxSubmitLinkTop);

    AjaxSubmitLink ajaxSubmitLinkBottom = new AjaxSubmitLink("saveBottom") {

        @Override
        protected void onSubmit(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {

            ajaxRequestTarget.add(componentsToUpdateList.toArray(new Component[componentsToUpdateList.size()]));
            successMessageTop.setVisible(true);
            successMessageBottom.setVisible(true);
            ajaxRequestTarget.add(successMessageTop);
            ajaxRequestTarget.add(successMessageBottom);
            ajaxRequestTarget.appendJavaScript(RadarApplication.FORM_IS_DIRTY_FALSE_SCRIPT);
        }

        @Override
        protected void onError(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
            ajaxRequestTarget.add(componentsToUpdateList.toArray(new Component[componentsToUpdateList.size()]));
            successMessageTop.setVisible(false);
            successMessageBottom.setVisible(false);
            ajaxRequestTarget.add(successMessageTop);
            ajaxRequestTarget.add(successMessageBottom);
        }
    };

    ajaxSubmitLinkBottom.add(new AttributeModifier("value", new AbstractReadOnlyModel() {
        @Override
        public Object getObject() {
            return patientModel.getObject() == null ? "Add this patient" : "Update";
        }
    }));

    form.add(ajaxSubmitLinkBottom);

    if (model.getObject().isLinked()) {
        for (Component component : nonEditableComponents) {
            component.setEnabled(false);
        }
    }
}

From source file:org.patientview.radar.web.panels.generic.GenericDemographicsPanel.java

License:Open Source License

private void init(Patient patient) {
    setOutputMarkupId(true);/*from   w w  w .  ja  va  2  s  . c o  m*/
    setOutputMarkupPlaceholderTag(true);

    List<Component> nonEditableComponents = new ArrayList<Component>();

    final ProfessionalUser user = (ProfessionalUser) RadarSecuredSession.get().getUser();

    if (patient.getDateReg() == null) {
        patient.setDateReg(new Date());
    }

    // components to update on ajax refresh
    final List<Component> componentsToUpdateList = new ArrayList<Component>();

    // add form
    final IModel<Patient> model = new Model(patient);

    //Error Message
    String message = "Please complete all mandatory fields";
    final LabelMessage labelMessage = new LabelMessage();
    labelMessage.setMessage(message);
    final PropertyModel<LabelMessage> messageModel = new PropertyModel<LabelMessage>(labelMessage, "message");

    // no exist data in patient table, then use the user name to populate.
    if (patient.getSurname() == null || patient.getForename() == null) {

        String name = utilityManager.getUserName(patient.getNhsno());

        if (name != null && !"".equals(name)) {
            // split the user name with a space
            String[] names = name.split(" ");
            if (names != null && names.length >= 2) {
                patient.setForename(name.substring(0, name.indexOf(names[names.length - 1])));
                patient.setSurname(names[names.length - 1]);

            } else {
                patient.setForename(name);
            }
        }
    }

    Form<Patient> form = new Form<Patient>("form", new CompoundPropertyModel(model)) {
        @Override
        protected void onSubmit() {

            Patient patient = getModel().getObject();

            // check dob exists
            if (patient.getDob() != null) {
                // make sure diagnosis date is after dob
                if (patient.getDateOfGenericDiagnosis() != null
                        && patient.getDateOfGenericDiagnosis().compareTo(patient.getDob()) < 0) {
                    get("dateOfGenericDiagnosisContainer:dateOfGenericDiagnosis")
                            .error("Your diagnosis date cannot be before your date of birth");
                }
            }

            // Leaving this in, saved to the DB table
            patient.setGeneric(true);

            try {
                /** At this point we either have
                 1) A new patient we would like to register
                 2) A link patient we would like to register
                 3) An existing linked patient we would like to update changes to the Patient table
                 4) An existing patient we would like to update changes to the Patient table **/
                userManager.addPatientUserOrUpdatePatient(patient);

            } catch (RegisterException re) {
                LOGGER.error("Registration Exception", re);
                String message = "Failed to register patient: " + re.getMessage();
                labelMessage.setMessage(message);
                error(message);
            } catch (Exception e) {
                String message = "Error registering new patient to accompany this demographic";
                LOGGER.error("Unknown error", e);
                error(message);
            }
        }
    };

    add(form);

    WebMarkupContainer patientDetail = new PatientDetailPanel("patientDetail", patient, "Demographics");
    patientDetail.setOutputMarkupId(true);
    patientDetail.setOutputMarkupPlaceholderTag(true);
    form.add(patientDetail);
    componentsToUpdateList.add(patientDetail);

    RadarRequiredTextField surname = new RadarRequiredTextField("surname", form, componentsToUpdateList);
    RadarRequiredTextField forename = new RadarRequiredTextField("forename", form, componentsToUpdateList);
    TextField alias = new TextField("surnameAlias");
    RadarRequiredDateTextField dateOfBirth = new RadarRequiredDateTextField("dob", form,
            componentsToUpdateList);

    form.add(surname, forename, alias, dateOfBirth);
    nonEditableComponents.add(surname);
    nonEditableComponents.add(forename);
    nonEditableComponents.add(dateOfBirth);
    // Sex
    RadarRequiredDropdownChoice sex = new RadarRequiredDropdownChoice("sexModel", patientManager.getSexes(),
            new ChoiceRenderer<Sex>("type", "id"), form, componentsToUpdateList);

    nonEditableComponents.add(sex);

    // Ethnicity
    DropDownChoice<Ethnicity> ethnicity = new DropDownChoice<Ethnicity>("ethnicity",
            utilityManager.getEthnicities(), new ChoiceRenderer<Ethnicity>("name", "id"));
    form.add(sex, ethnicity);

    // Address fields
    TextField address1 = new TextField("address1");
    TextField address2 = new TextField("address2");
    TextField address3 = new TextField("address3");
    TextField address4 = new TextField("address4");
    RadarTextFieldWithValidation postcode = new RadarTextFieldWithValidation("postcode",
            new PatternValidator("[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$"), form,
            componentsToUpdateList);
    form.add(address1, address2, address3, address4, postcode);

    nonEditableComponents.add(address1);
    nonEditableComponents.add(address2);
    nonEditableComponents.add(address3);
    nonEditableComponents.add(address4);
    nonEditableComponents.add(postcode);
    // More info
    Label nhsNumber = new Label("nhsno");

    WebMarkupContainer nhsNumberContainer = new WebMarkupContainer("nhsNumberContainer");

    nhsNumberContainer.add(nhsNumber);

    // add new ids section
    final List<Component> addIdComponentsToUpdate = new ArrayList<Component>();

    IModel<AddIdModel> addIdModel = new Model<AddIdModel>(new AddIdModel());
    Form<AddIdModel> addIdForm = new Form<AddIdModel>("addIdForm", new CompoundPropertyModel(addIdModel)) {
        @Override
        protected void onSubmit() {
            AddIdModel idModel = getModel().getObject();
            Patient patient = model.getObject();
            String id = idModel.getId();
            if (idModel.getIdType() != null) {
                if (idModel.getIdType().equals(IdType.CHANNELS_ISLANDS)) {
                    patient.setChannelIslandsId(id);
                }
                if (idModel.getIdType().equals(IdType.HOSPITAL_NUMBER)) {
                    patient.setHospitalnumber(id);
                }
                if (idModel.getIdType().equals(IdType.INDIA)) {
                    patient.setIndiaId(id);
                }
                if (idModel.getIdType().equals(IdType.RENAL_REGISTRY_NUMBER)) {
                    patient.setRrNo(id);
                }
                if (idModel.getIdType().equals(IdType.REPUBLIC_OF_IRELAND)) {
                    patient.setRepublicOfIrelandId(id);
                }
                if (idModel.getIdType().equals(IdType.UK_TRANSPLANT_NUMBER)) {
                    patient.setUktNo(id);
                }
            }
        }

    };

    AjaxSubmitLink addIdSubmit = new AjaxSubmitLink("addIdSubmit") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            ComponentHelper.updateComponentsIfParentIsVisible(target, addIdComponentsToUpdate);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            ComponentHelper.updateComponentsIfParentIsVisible(target, addIdComponentsToUpdate);
        }
    };

    TextField addIdValue = new TextField("id");

    DropDownChoice addIdType = null;

    // Link patients should not be able to add hospital numbers
    if (!patient.isLinked()) {
        addIdType = new DropDownChoice("idType",
                Arrays.asList(IdType.HOSPITAL_NUMBER, IdType.RENAL_REGISTRY_NUMBER, IdType.UK_TRANSPLANT_NUMBER,
                        IdType.REPUBLIC_OF_IRELAND, IdType.CHANNELS_ISLANDS, IdType.INDIA),
                new ChoiceRenderer());
    } else {
        addIdType = new DropDownChoice("idType",
                Arrays.asList(IdType.RENAL_REGISTRY_NUMBER, IdType.UK_TRANSPLANT_NUMBER,
                        IdType.REPUBLIC_OF_IRELAND, IdType.CHANNELS_ISLANDS, IdType.INDIA),
                new ChoiceRenderer());
    }

    addIdForm.add(addIdValue, addIdType, addIdSubmit);
    form.add(addIdForm);

    TextField hospitalNumber = new TextField("hospitalnumber");
    WebMarkupContainer hospitalNumberContainer = new WebMarkupContainer("hospitalNumberContainer") {
        @Override
        public boolean isVisible() {
            if (model.getObject().getHospitalnumber() != null) {
                if (!model.getObject().getHospitalnumber().isEmpty()) {
                    return true;
                }
            }
            return false;
        }
    };

    hospitalNumberContainer.add(hospitalNumber);
    nonEditableComponents.add(hospitalNumber);

    TextField renalRegistryNumber = new TextField("rrNo");
    WebMarkupContainer renalRegistryNumberContainer = new WebMarkupContainer("renalRegistryNumberContainer") {
        @Override
        public boolean isVisible() {
            if (model.getObject().getRrNo() != null) {
                if (!model.getObject().getRrNo().isEmpty()) {
                    return true;
                }
            }
            return false;
        }
    };
    renalRegistryNumberContainer.add(renalRegistryNumber);

    TextField ukTransplantNumber = new TextField("uktNo");

    WebMarkupContainer ukTransplantNumberContainer = new WebMarkupContainer("ukTransplantNumberContainer") {
        @Override
        public boolean isVisible() {
            if (model.getObject().getUktNo() != null) {
                if (!model.getObject().getUktNo().isEmpty()) {
                    return true;
                }
            }
            return false;
        }
    };
    ukTransplantNumberContainer.add(ukTransplantNumber);

    // add other generic ids
    TextField republicOfIrelandId = new TextField("republicOfIrelandId");

    WebMarkupContainer republicOfIrelandIdContainer = new WebMarkupContainer("republicOfIrelandIdContainer") {
        @Override
        public boolean isVisible() {
            if (model.getObject().getRepublicOfIrelandId() != null) {
                if (!model.getObject().getRepublicOfIrelandId().isEmpty()) {
                    return true;
                }
            }
            return false;
        }
    };
    republicOfIrelandIdContainer.add(republicOfIrelandId);

    TextField isleOfManId = new TextField("isleOfManId");

    WebMarkupContainer isleOfManIdContainer = new WebMarkupContainer("isleOfManIdContainer") {
        @Override
        public boolean isVisible() {
            if (model.getObject().getIsleOfManId() != null) {
                if (!model.getObject().getIsleOfManId().isEmpty()) {
                    return true;
                }
            }
            return false;
        }
    };

    isleOfManIdContainer.add(isleOfManId);

    TextField channelIslandsId = new TextField("channelIslandsId");

    WebMarkupContainer channelIslandsIdContainer = new WebMarkupContainer("channelIslandsIdContainer") {
        @Override
        public boolean isVisible() {
            if (model.getObject().getChannelIslandsId() != null) {
                if (!model.getObject().getChannelIslandsId().isEmpty()) {
                    return true;
                }
            }
            return false;
        }
    };
    channelIslandsIdContainer.add(channelIslandsId);

    TextField indiaId = new TextField("indiaId");

    WebMarkupContainer indiaIdContainer = new WebMarkupContainer("indiaIdContainer") {
        @Override
        public boolean isVisible() {
            if (model.getObject().getIndiaId() != null) {
                if (!model.getObject().getIndiaId().isEmpty()) {
                    return true;
                }
            }
            return false;
        }
    };
    indiaIdContainer.add(indiaId);

    addIdComponentsToUpdate.add(hospitalNumberContainer);
    addIdComponentsToUpdate.add(renalRegistryNumberContainer);
    addIdComponentsToUpdate.add(ukTransplantNumberContainer);
    addIdComponentsToUpdate.add(republicOfIrelandIdContainer);
    addIdComponentsToUpdate.add(isleOfManIdContainer);
    addIdComponentsToUpdate.add(channelIslandsIdContainer);
    addIdComponentsToUpdate.add(indiaIdContainer);

    for (Component component : Arrays.asList(hospitalNumberContainer, renalRegistryNumberContainer,
            ukTransplantNumberContainer, republicOfIrelandIdContainer, isleOfManIdContainer,
            channelIslandsIdContainer, indiaIdContainer)) {
        component.setOutputMarkupPlaceholderTag(true);
    }

    form.add(hospitalNumberContainer, nhsNumberContainer, renalRegistryNumberContainer,
            ukTransplantNumberContainer);
    form.add(republicOfIrelandIdContainer, isleOfManIdContainer, channelIslandsIdContainer, indiaIdContainer);

    // Consultant and renal unit
    final ClinicianDropDown clinician = new ClinicianDropDown("clinician", user, form.getModelObject());
    form.add(clinician);

    Label sourceUnitCodeLabel = new Label("sourceUnitCodeLabel", "Linked to") {
        @Override
        public boolean isVisible() {
            return model.getObject().isLinked();

        }

    };

    String sourceUnitNameLabelValue = model.getObject().getPatientLinkUnitCode() != null
            ? utilityManager.getCentre(model.getObject().getPatientLinkUnitCode()).getName()
            : "";

    Label sourceUnitCode = new Label("sourceUnitCode", sourceUnitNameLabelValue) {
        @Override
        public boolean isVisible() {
            return model.getObject().isLinked();

        }
    };
    form.add(sourceUnitCodeLabel, sourceUnitCode);

    final DropDownChoice<Centre> renalUnit = new PatientCentreDropDown("renalUnit", user, patient, form,
            componentsToUpdateList);

    renalUnit.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            Patient patient = model.getObject();
            if (patient != null) {
                clinician.updateCentre(
                        patient.getRenalUnit() != null ? patient.getRenalUnit().getUnitCode() : null);
            }

            // re-render the component
            clinician.clearInput();
            target.add(clinician);
        }
    });

    form.add(renalUnit);

    final IModel<String> consentUserModel = new Model<String>(
            utilityManager.getUserFullName(patient.getRadarConsentConfirmedByUserId()));

    final Label tickConsentUser = new Label("radarConsentConfirmedByUserId", consentUserModel) {
        @Override
        public boolean isVisible() {
            return StringUtils.isNotEmpty(consentUserModel.getObject());
        }
    };
    tickConsentUser.setOutputMarkupId(true);
    tickConsentUser.setOutputMarkupPlaceholderTag(true);
    form.add(tickConsentUser);

    final RadarRequiredCheckBox consent = new RadarRequiredCheckBox("consent", form, componentsToUpdateList);

    consent.add(new AjaxFormComponentUpdatingBehavior("onclick") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {

            target.add(tickConsentUser);

            if (consent.getModel().getObject().equals(Boolean.TRUE)) {
                model.getObject()
                        .setRadarConsentConfirmedByUserId(RadarSecuredSession.get().getUser().getUserId());
                consentUserModel.setObject(RadarSecuredSession.get().getUser().getName());
                tickConsentUser.setVisible(true);

            } else {
                tickConsentUser.setVisible(false);
            }
        }
    });

    form.add(consent);

    form.add(new ExternalLink("consentFormsLink", "http://www.rarerenal.org/join/criteria-and-consent/"));

    // add generic fields
    TextField emailAddress = new TextField("emailAddress");
    TextField phone1 = new TextField("telephone1");
    TextField phone2 = new TextField("telephone2");

    nonEditableComponents.add(phone1);

    RadarTextFieldWithValidation mobile = new RadarTextFieldWithValidation("mobile",
            new PatternValidator(MetaPattern.DIGITS), form, componentsToUpdateList);

    RadarRequiredDropdownChoice genericDiagnosis = new RadarRequiredDropdownChoice("genericDiagnosisModel",
            genericDiagnosisManager.getByDiseaseGroup(patient.getDiseaseGroup()),
            new ChoiceRenderer("term", "id"), form, componentsToUpdateList);

    final IModel<Boolean> diagnosisDateVisibility = new Model<Boolean>(Boolean.FALSE);

    final CheckBox diagnosisDateSelect = new CheckBox("diagnosisDateSelect", new Model<Boolean>(Boolean.FALSE));
    model.getObject().setDiagnosisDateSelect(model.getObject().getDiagnosisDateSelect() == Boolean.TRUE);

    diagnosisDateSelect.add(new AjaxFormComponentUpdatingBehavior("onClick") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            diagnosisDateVisibility.setObject(diagnosisDateSelect.getModel().getObject());
            target.add(componentsToUpdateList.toArray(new Component[componentsToUpdateList.size()]));
        }
    });

    RadarRequiredDateTextField dateOfGenericDiagnosis = new RadarRequiredDateTextField("dateOfGenericDiagnosis",
            form, componentsToUpdateList);

    form.add(diagnosisDateSelect);

    MarkupContainer dateOfGenericDiagnosisContainer = new WebMarkupContainer(
            "dateOfGenericDiagnosisContainer") {
        @Override
        public boolean isVisible() {
            if (diagnosisDateVisibility.getObject()) {
                return false;
            } else {
                return true;
            }
        }
    };
    dateOfGenericDiagnosisContainer.add(dateOfGenericDiagnosis);
    componentsToUpdateList.add(dateOfGenericDiagnosisContainer);
    dateOfGenericDiagnosisContainer.setOutputMarkupId(true);
    dateOfGenericDiagnosisContainer.setOutputMarkupPlaceholderTag(true);

    this.dateOfGenericDiagnosisContainer = dateOfGenericDiagnosisContainer;

    TextArea otherClinicianAndContactInfo = new TextArea("otherClinicianAndContactInfo");
    TextArea comments = new TextArea("comments");

    form.add(emailAddress, phone1, phone2, mobile, genericDiagnosis, dateOfGenericDiagnosisContainer,
            otherClinicianAndContactInfo, comments);

    RadioGroup<Patient.RRTModality> rrtModalityRadioGroup = new RadioGroup<Patient.RRTModality>(
            "rrtModalityEunm");
    rrtModalityRadioGroup.add(new Radio("hd", new Model(Patient.RRTModality.HD)));
    rrtModalityRadioGroup.add(new Radio("pd", new Model(Patient.RRTModality.PD)));
    rrtModalityRadioGroup.add(new Radio("tx", new Model(Patient.RRTModality.Tx)));
    rrtModalityRadioGroup.add(new Radio("none", new Model(Patient.RRTModality.NONE)));

    form.add(rrtModalityRadioGroup);

    RadarComponentFactory.getSuccessMessageLabel("successMessage", form, componentsToUpdateList);

    RadarComponentFactory.getSuccessMessageLabel("successMessageUp", form, componentsToUpdateList);

    RadarComponentFactory.getMessageLabel("errorMessage", form, messageModel, componentsToUpdateList);
    RadarComponentFactory.getMessageLabel("errorMessageUp", form, messageModel, componentsToUpdateList);

    AjaxSubmitLink ajaxSubmitLinkTop = new AjaxSubmitLink("saveTop") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdateList);
            target.appendJavaScript(RadarApplication.FORM_IS_DIRTY_FALSE_SCRIPT);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdateList);
        }
    };

    AjaxSubmitLink ajaxSubmitLinkBottom = new AjaxSubmitLink("saveBottom") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdateList);
            target.appendJavaScript(RadarApplication.FORM_IS_DIRTY_FALSE_SCRIPT);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdateList);
        }
    };

    form.add(ajaxSubmitLinkTop);
    form.add(ajaxSubmitLinkBottom);

    if (patient.isLinked()) {
        for (Component component : nonEditableComponents) {
            component.setEnabled(false);
        }
    }

}

From source file:org.wicketstuff.minis.behavior.EnabledModelBehavior.java

License:Apache License

@Override
public void onConfigure(final Component component) {
    super.onConfigure(component);
    Boolean enabled = getDependentModel().getObject();
    component.setEnabled(enabled != null && enabled);
}