Package org.openmrs.module.htmlformentry.widget

Examples of org.openmrs.module.htmlformentry.widget.Option


            drugLabels = Arrays.asList(parameters.get(FIELD_DRUG_LABELS).split(","));
        }

    // fill drop down with drug names from database
    List<Option> options = new ArrayList<Option>();
    options.add(new Option("", "", false));

    // drugNames is comma separated list which can contain ID, UUID or drugname
    StringTokenizer tokenizer = new StringTokenizer(drugNames, ",");
    int drugListIndexPos = 0;
        String displayText = "";
        DrugOrderField dof = new DrugOrderField();
    while (tokenizer.hasMoreElements()) {
      String drugName = (String) tokenizer.nextElement();
      Drug drug = null;

      // see if this is a uuid
      if (HtmlFormEntryUtil.isValidUuidFormat(drugName.trim())) {
        drug = conceptService.getDrugByUuid(drugName.trim());
      }

      // if we didn't find by id, find by uuid or name
      if (drug == null){
        drug = conceptService.getDrugByNameOrId(drugName.trim());
      }

      if (drug != null) {
          displayText = drug.getName();
          if (drugLabels != null) {
              displayText = drugLabels.get(drugListIndexPos);
          }
        options.add(new Option(displayText, drug.getDrugId().toString(), false));
        if (drugsUsedAsKey == null) {
            drugsUsedAsKey = new ArrayList<Drug>();
        }
        drugsUsedAsKey.add(drug);
        DrugOrderAnswer doa = new DrugOrderAnswer(drug, displayText);
        dof.addDrugOrderAnswer(doa);
        drugListIndexPos ++;
      } else if (drugName.length() > 0 && drugName.charAt(0) == '/' && drugName.charAt(drugName.length()-1) == '/'){
          options.add(new Option("[ " + drugName.substring(1,drugName.length()-1) + " ]", "~", false));
      } else {
          throw new IllegalArgumentException("No Drug found for drug name/id/uuid " + drugName);
      }
    }

    if (drugsUsedAsKey == null)
      throw new IllegalArgumentException("You must provide a valid drug name, or a valid ID or a valid UUID in " + parameters);

        // there need to be the same number of drugs as drug labels
        if (drugLabels != null && drugsUsedAsKey.size() != drugLabels.size())
            throw new IllegalArgumentException("There are a different number of drugLabels (" + drugLabels.size() + ") than drugs (" + drugsUsedAsKey.size() + ").");


        // Register Drug Widget
        if (checkbox && drugsUsedAsKey.size() == 1){
            CheckboxWidget cb = new CheckboxWidget();
            cb.setLabel(displayText);
            cb.setValue(drugsUsedAsKey.get(0).getDrugId().toString());
            drugWidget = cb;
        } else {
            DropdownWidget dw = new DropdownWidget();
            dw.setOptions(options);
            drugWidget = dw;
        }
        context.registerWidget(drugWidget);
        drugErrorWidget = new ErrorWidget();
        context.registerErrorWidget(drugWidget, drugErrorWidget);

    //start date
    startDateWidget = new DateWidget();
        startDateErrorWidget = new ErrorWidget();
        context.registerWidget(startDateWidget);
        context.registerErrorWidget(startDateWidget, startDateErrorWidget);

        if (!hideDoseAndFrequency){
        // dose validation by drug is done in validateSubmission()
        doseWidget = new NumberFieldWidget(0d, 9999999d, true);
        //set default value (maybe temporarily)
        String defaultDoseStr = parameters.get(CONFIG_DEFAULT_DOSE);
        if (!StringUtils.isEmpty(defaultDoseStr)){
            try {
                defaultDose = Double.valueOf(defaultDoseStr);
                doseWidget.setInitialValue(defaultDose);
            } catch (Exception ex){
                    throw new RuntimeException("optional attribute 'defaultDose' must be numeric or empty.");
            }
        }

        doseErrorWidget = new ErrorWidget();
        context.registerWidget(doseWidget);
        context.registerErrorWidget(doseWidget, doseErrorWidget);

        createFrequencyWidget(context, mss);

        createFrequencyWeekWidget(context, mss);
        }

        if (!usingDurationField){
        discontinuedDateWidget = new DateWidget();
        discontinuedDateErrorWidget = new ErrorWidget();
        context.registerWidget(discontinuedDateWidget);
        context.registerErrorWidget(discontinuedDateWidget, discontinuedDateErrorWidget);
        }
    if (parameters.get(FIELD_DISCONTINUED_REASON) != null){
        String discReasonConceptStr = (String) parameters.get(FIELD_DISCONTINUED_REASON);
        Concept discontineReasonConcept = HtmlFormEntryUtil.getConcept(discReasonConceptStr);
        if (discontineReasonConcept == null)
            throw new IllegalArgumentException("discontinuedReasonConceptId is not set to a valid conceptId or concept UUID");
        dof.setDiscontinuedReasonQuestion(discontineReasonConcept);

        discontinuedReasonWidget = new DropdownWidget();
        discontinuedReasonErrorWidget = new ErrorWidget();

        List<Option> discOptions = new ArrayList<Option>();
        discOptions.add(new Option("", "", false));

        if (parameters.get(FIELD_DISCONTINUED_REASON_ANSWERS) != null){
            //setup a list of the reason concepts
            List<Concept> discReasons = new ArrayList<Concept>();
            String discAnswersString = (String) parameters.get(FIELD_DISCONTINUED_REASON_ANSWERS);
            String[] strDiscAnswers = discAnswersString.split(",");
            for (int i = 0; i < strDiscAnswers.length; i++){
                String thisAnswer = strDiscAnswers[i];
                Concept answer = HtmlFormEntryUtil.getConcept(thisAnswer, "discontinueReasonAnswers includes a value that is not a valid conceptId or concept UUID");
                  discReasons.add(answer);
            }

            if (parameters.get(FIELD_DISCONTINUED_REASON_ANSWER_LABELS) != null){
                // use the listed discontinueReasons, and use labels:
                String discLabelsString = parameters.get(FIELD_DISCONTINUED_REASON_ANSWER_LABELS);
                String[] strDiscAnswerLabels = discLabelsString.split(",");
                //a little validation:
                if (strDiscAnswerLabels.length != discReasons.size())
                    throw new RuntimeException("discontinueReasonAnswers and discontinueReasonAnswerLabels must contain the same number of members.");
                for (int i = 0; i < strDiscAnswerLabels.length; i ++ ){
                    discOptions.add(new Option( strDiscAnswerLabels[i], discReasons.get(i).getConceptId().toString(),false));
                    dof.addDiscontinuedReasonAnswer(new ObsFieldAnswer(strDiscAnswerLabels[i].trim(), discReasons.get(i)));
                }
            } else {
                // use the listed discontinueReasons, and use their ConceptNames.
                for (Concept c: discReasons){
                    discOptions.add(new Option( c.getBestName(Context.getLocale()).getName(), c.getConceptId().toString(),false));
                    dof.addDiscontinuedReasonAnswer(new ObsFieldAnswer(c.getBestName(Context.getLocale()).getName(), c));
                }
            }
        } else {
            //just use the conceptAnswers
            for (ConceptAnswer ca : discontineReasonConcept.getAnswers()){
                discOptions.add(new Option( ca.getAnswerConcept().getBestName(Context.getLocale()).getName(), ca.getAnswerConcept().getConceptId().toString(),false));
                dof.addDiscontinuedReasonAnswer(new ObsFieldAnswer(ca.getAnswerConcept().getBestName(Context.getLocale()).getName(), ca.getAnswerConcept()));
            }
        }
        if (discOptions.size() == 1)
            throw new IllegalArgumentException("discontinue reason Concept doesn't have any ConceptAnswers");
View Full Code Here


      frequencyWeekErrorWidget = new ErrorWidget();
      // fill frequency drop down lists (ENTER, EDIT)
      List<Option> weekOptions = new ArrayList<Option>();
      if (context.getMode() != Mode.VIEW ) {
        for (int i = 7; i >= 1; i--) {
            weekOptions.add(new Option(i + " " + mss.getMessage("DrugOrder.frequency.days") + "/"  + mss.getMessage("DrugOrder.frequency.week") , String.valueOf(i), false));
          }
      }
      frequencyWeekWidget.setOptions(weekOptions);
      context.registerWidget(frequencyWeekWidget);
      context.registerErrorWidget(frequencyWeekWidget, frequencyWeekErrorWidget);
View Full Code Here

      frequencyErrorWidget = new ErrorWidget();
      // fill frequency drop down lists (ENTER, EDIT)
      List<Option> freqOptions = new ArrayList<Option>();
      if (context.getMode() != Mode.VIEW ) {
        for (int i = 1; i <= 10; i++) {
            freqOptions.add(new Option(i + "/" + mss.getMessage("DrugOrder.frequency.day"), String.valueOf(i), false));
        }
      }
      frequencyWidget.setOptions(freqOptions);
      context.registerWidget(frequencyWidget);
      context.registerErrorWidget(frequencyWidget, frequencyErrorWidget);
View Full Code Here

    }
    else if (FIELD_GENDER.equalsIgnoreCase(field)) {
      MessageSourceService msg = Context.getMessageSourceService();
      genderWidget = new DropdownWidget();
      genderErrorWidget = new ErrorWidget();
      genderWidget.addOption(new Option(msg.getMessage("Patient.gender.male"), "M", false));
      genderWidget.addOption(new Option(msg.getMessage("Patient.gender.female"), "F", false));
      createWidgets(context, genderWidget, genderErrorWidget, existingPatient != null ? existingPatient.getGender() : null);
    }
    else if (FIELD_AGE.equalsIgnoreCase(field)) {
      ageWidget = new NumberFieldWidget(0d, 200d, false);
      ageErrorWidget = new ErrorWidget();
      createWidgets(context, ageWidget, ageErrorWidget, existingPatient != null ? existingPatient.getAge() : null);
    }
    else if (FIELD_BIRTH_DATE.equalsIgnoreCase(field)) {
      birthDateWidget = new DateWidget();
      birthDateErrorWidget = new ErrorWidget();
      createWidgets(context, birthDateWidget, birthDateErrorWidget, existingPatient != null ? existingPatient.getBirthdate() : null);
    }
    else if (FIELD_BIRTH_DATE_OR_AGE.equalsIgnoreCase(field)) {
      ageWidget = new NumberFieldWidget(0d, 200d, false);
      ageErrorWidget = new ErrorWidget();
      createWidgets(context, ageWidget, ageErrorWidget, existingPatient != null ? existingPatient.getAge() : null);

      birthDateWidget = new DateWidget();
      birthDateErrorWidget = new ErrorWidget();
      createWidgets(context, birthDateWidget, birthDateErrorWidget, existingPatient != null ? existingPatient.getBirthdate() : null);

    }
    else if (FIELD_IDENTIFIER.equalsIgnoreCase(field)) {

      PatientIdentifierType idType = HtmlFormEntryUtil.getPatientIdentifierType(attributes.get("identifierTypeId"));
     
      identifierTypeValueWidget = new TextFieldWidget();
      identifierTypeValueErrorWidget = new ErrorWidget();
      String initialValue = null;
      if (existingPatient != null) {
        if (idType == null) {
          if (existingPatient.getPatientIdentifier() != null) {
            initialValue = existingPatient.getPatientIdentifier().getIdentifier();
          }
        } else {
          if (existingPatient.getPatientIdentifier(idType) != null) {
            initialValue = existingPatient.getPatientIdentifier(idType).getIdentifier();
          }
        }
      }
      createWidgets(context, identifierTypeValueWidget, identifierTypeValueErrorWidget, initialValue);

      if (idType != null) {
        identifierTypeWidget = new HiddenFieldWidget();
        createWidgets(context, identifierTypeWidget, null, idType.getId().toString());
      }
      else {
        identifierTypeWidget = new DropdownWidget();
        List<PatientIdentifierType> patientIdentifierTypes = HtmlFormEntryUtil.getPatientIdentifierTypes();

        for (PatientIdentifierType patientIdentifierType : patientIdentifierTypes) {
          ((DropdownWidget) identifierTypeWidget).addOption(new Option(patientIdentifierType.getName(), patientIdentifierType
              .getPatientIdentifierTypeId().toString(), false));
        }

        createWidgets(context, identifierTypeWidget, null,
            existingPatient != null && existingPatient.getPatientIdentifier() != null ? existingPatient.getPatientIdentifier()
                .getIdentifierType().getId() : null);
      }
    }
    else if (FIELD_IDENTIFIER_LOCATION.equalsIgnoreCase(field)) {
      identifierLocationWidget = new DropdownWidget();
      identifierLocationErrorWidget = new ErrorWidget();

            Location defaultLocation = existingPatient != null
          && existingPatient.getPatientIdentifier() != null ? existingPatient.getPatientIdentifier().getLocation() : null;
      defaultLocation = defaultLocation == null ? context.getDefaultLocation() : defaultLocation;
            identifierLocationWidget.setInitialValue(defaultLocation);

            List<Option> locationOptions = new ArrayList<Option>();
            for(Location location:Context.getLocationService().getAllLocations()) {
                Option option = new Option(location.getName(), location.getId().toString(), location.equals(defaultLocation));
                locationOptions.add(option);
            }
            Collections.sort(locationOptions, new OptionComparator());

            // if initialValueIsSet=false, no initial/default location, hence this shows the 'select input' field as first option
            boolean initialValueIsSet = !(defaultLocation == null);
            ((DropdownWidget) identifierLocationWidget).addOption(new Option(Context.getMessageSourceService().getMessage("htmlformentry.chooseALocation"), "", !initialValueIsSet));
            if (!locationOptions.isEmpty()) {
                    for(Option option: locationOptions){
                    ((DropdownWidget) identifierLocationWidget).addOption(option);
                    }
            }
View Full Code Here

    private Widget buildDropdownWidget(Integer size){
        Widget dropdownWidget = new DropdownWidget(size);
        if(size==1 || !required){
            // show an empty option when size =1, even if required =true
            ((DropdownWidget) dropdownWidget).addOption(new Option());
        }
        return dropdownWidget;
    }
View Full Code Here

        if (conceptLabels != null && i < conceptLabels.size()) {
          label = conceptLabels.get(i);
        } else {
          label = c.getBestName(Context.getLocale()).getName();
        }
        ((SingleOptionWidget) valueWidget).addOption(new Option(label, c.getConceptId().toString(), false));
      }
      if (existingObs != null) {
        valueWidget.setInitialValue(existingObs.getConcept());
      } else if (defaultValue != null && Mode.ENTER.equals(context.getMode())) {
        Concept initialValue = HtmlFormEntryUtil.getConcept(defaultValue);
        if (initialValue == null) {
          throw new IllegalArgumentException("Invalid default value. Cannot find concept: " + defaultValue);
        }
        valueWidget.setInitialValue(initialValue);
      }
      answerLabel = getValueLabel();
    } else {

      // Obs of datatypes date, time, and datetime support the attributes
      // defaultDatetime. Make sure this date format string matches the
      // format documented at
      // https://wiki.openmrs.org/display/docs/HTML+Form+Entry+Module+HTML+Reference#HTMLFormEntryModuleHTMLReference-%3Cobs%3E
      // See <obs> section, attributes defaultDatetime and
      // defaultObsDatetime
      String defaultDatetimeFormat = "yyyy-MM-dd-HH-mm";

      if (concept.getDatatype().isNumeric()) {
        if (parameters.get("answers") != null) {
          try {
            for (StringTokenizer st = new StringTokenizer(parameters.get("answers"), ", "); st.hasMoreTokens();) {
              Number answer = Double.valueOf(st.nextToken());
              numericAnswers.add(answer);
            }
          }
          catch (Exception ex) {
            throw new RuntimeException("Error in answer list for concept " + concept.getConceptId() + " ("
                    + ex.toString() + "): " + conceptAnswers);
          }
        }
        ConceptNumeric cn;
                if (concept instanceof ConceptNumeric) {
                    cn = (ConceptNumeric) concept;
                } else {
                    cn = Context.getConceptService().getConceptNumeric(concept.getConceptId());
                }
        // added to avoid creating this widget when a checkbox is needed
                if (numericAnswers.size() == 0) {
                    if (!"checkbox".equals(parameters.get("style"))) {
                        valueWidget = new NumberFieldWidget(cn, parameters.get("size"));
                    } else {
                        // render CheckboxWidgets for <obs> tag with numeric datatype;
                        // i.e. <obs conceptId="1234" answer="8" answerLabel="Eight" style="checkbox"/>
                        if (parameters.get("answer") != null) {
                            try {
                                Number number = Double.valueOf(parameters.get("answer"));
                                numericAnswers.add(number);
                                answerLabel = parameters.get("answerLabel");
                                if (number != null) {
                                    valueWidget = new CheckboxWidget(answerLabel, number.toString());
                                }

                            } catch (Exception ex) {
                                throw new RuntimeException("Error in answer for concept " + concept.getConceptId() + " ("
                                        + ex.toString() + "): ");
                            }
                        }
                    }
                } else {
          if ("radio".equals(parameters.get("style"))) {
            valueWidget = new RadioButtonsWidget();
            if (answerSeparator != null) {
              ((RadioButtonsWidget) valueWidget).setAnswerSeparator(answerSeparator);
                        }
          } else { // dropdown
                        valueWidget = buildDropdownWidget(size);
          }
          // need to make sure we have the initialValue too
          Number lookFor = existingObs == null ? null : existingObs.getValueNumeric();
          for (int i = 0; i < numericAnswers.size(); ++i) {
            Number n = numericAnswers.get(i);
            if (lookFor != null && lookFor.equals(n))
              lookFor = null;
            String label = null;
            if (answerLabels != null && i < answerLabels.size()) {
              label = answerLabels.get(i);
            } else {
              label = n.toString();
            }
            ((SingleOptionWidget) valueWidget).addOption(new Option(label, n.toString(), false));
          }
          // if lookFor is still non-null, we need to add it directly as
          // an option:
          if (lookFor != null)
            ((SingleOptionWidget) valueWidget)
                    .addOption(new Option(lookFor.toString(), lookFor.toString(), true));
        }

        if (valueWidget != null) {
          boolean isPrecise = cn != null ? cn.isPrecise() : true; // test data is missing concept numerics
          Number initialValue = null;

          if (existingObs != null && existingObs.getValueNumeric() != null) {
            // for non-precise numeric obs, initial value should be rendered as an integer
            initialValue = isPrecise ? ((Number) existingObs.getValueNumeric()) : existingObs.getValueNumeric().intValue();
          } else if (defaultValue != null && Mode.ENTER.equals(context.getMode())) {
            try {
              initialValue = isPrecise ? ((Number) Double.valueOf(defaultValue)) : Integer.valueOf(defaultValue);
            } catch (NumberFormatException e) {
              throw new IllegalArgumentException("Default value " + defaultValue + " is not a valid " + (isPrecise ? "double" : "integer"), e);
            }
          }
          valueWidget.setInitialValue(initialValue);
        }

      } else if (concept.isComplex()) {
        valueWidget = new UploadWidget();
        String lookFor = existingObs == null ? null : existingObs.getValueComplex();
        Obs initialValue = null;
        if (lookFor != null) {
          initialValue = existingObs;
        }
        valueWidget.setInitialValue(initialValue);
      } else if (concept.getDatatype().isText()) {

        String initialValue = null;
        if (defaultValue != null && Mode.ENTER.equals(context.getMode())) {
          initialValue = defaultValue;
        }
        if (existingObs != null) {
          initialValue = existingObs.getValueText();
        }

        if (parameters.get("answers") != null) {
          try {
            for (StringTokenizer st = new StringTokenizer(parameters.get("answers"), ","); st.hasMoreTokens();) {
              textAnswers.add(st.nextToken());
            }
          }
          catch (Exception ex) {
            throw new RuntimeException("Error in answer list for concept " + concept.getConceptId() + " ("
                    + ex.toString() + "): " + conceptAnswers);
          }
        }

                // configure the special obs type that allows selection of a location (the location_id PK is stored as the valueText)
        if (isLocationObs) {

                    valueWidget = new DropdownWidget();
                    // if "answerLocationTags" attribute is present try to get locations by tags
                    List<Location> locationList = HtmlFormEntryUtil.getLocationsByTags(HtmlFormEntryConstants.ANSWER_LOCATION_TAGS, parameters);
                    if ((locationList == null) ||
                            (locationList != null && locationList.size()<1)){
                        // if no locations by tags are found then get all locations
                        locationList = Context.getLocationService().getAllLocations();
                    }

                    for (Location location : locationList) {
                            String label = HtmlFormEntryUtil.format(location);
                            Option option = new Option(label, location.getId().toString(), location.getId().toString().equals(initialValue));
                            locationOptions.add(option);
                       }
                    Collections.sort(locationOptions, new OptionComparator());

                    // if initialValueIsSet=false, no initial/default location, hence this shows the 'select input' field as first option
                    boolean initialValueIsSet = !(initialValue == null);
                    ((DropdownWidget)valueWidget).addOption(new Option(Context.getMessageSourceService().getMessage("htmlformentry.chooseALocation"),"",!initialValueIsSet));
                    if (!locationOptions.isEmpty()) {
                        for(Option option: locationOptions)
                            ((DropdownWidget)valueWidget).addOption(option);
                    }

        } else if ("person".equals(parameters.get("style"))) {
         
          List<PersonStub> options = new ArrayList<PersonStub>();
                    List<Option> personOptions = new ArrayList<Option>();
         
          // If specific persons are specified, display only those persons in order
          String personsParam = (String) parameters.get("persons");
          if (personsParam != null) {
            for (String s : personsParam.split(",")) {
              Person p = HtmlFormEntryUtil.getPerson(s);
              if (p == null) {
                throw new RuntimeException("Cannot find Person: " + s);
              }
              options.add(new PersonStub(p));
            }
          }
         
          // Only if specific person ids are not passed in do we get by user Role
          if (options.isEmpty()) {
           
            List<PersonStub> users = new ArrayList<PersonStub>();
           
            // If the "role" attribute is passed in, limit to users with this role
            if (parameters.get("role") != null) {
              Role role = Context.getUserService().getRole((String) parameters.get("role"));
              if (role == null) {
                throw new RuntimeException("Cannot find role: " + parameters.get("role"));
              } else {
                users = Context.getService(HtmlFormEntryService.class).getUsersAsPersonStubs(role.getRole());
              }
            }

            // Otherwise, limit to users with the default OpenMRS PROVIDER role,
            else {
              String defaultRole = OpenmrsConstants.PROVIDER_ROLE;
              Role role = Context.getUserService().getRole(defaultRole);
              if (role != null) {
                users = Context.getService(HtmlFormEntryService.class).getUsersAsPersonStubs(role.getRole());
              }
              // If this role isn't used, default to all Users
              if (users.isEmpty()) {
                users = Context.getService(HtmlFormEntryService.class).getUsersAsPersonStubs(null);
              }
            }
            options.addAll(users);
            //              sortOptions = true;
          }

          valueWidget = new PersonStubWidget(options);

        } else {
          if (textAnswers.size() == 0) {
            Integer rows = null;
            Integer cols = null;
            try {
              rows = Integer.valueOf(parameters.get("rows"));
            }
            catch (Exception ex) {}
            try {
              cols = Integer.valueOf(parameters.get("cols"));
            }
            catch (Exception ex) {}
            if (rows != null || cols != null || "textarea".equals(parameters.get("style"))) {
              valueWidget = new TextFieldWidget(rows, cols);
            } else {
              Integer textFieldSize = null;
              try {
                                textFieldSize = Integer.valueOf(parameters.get("size"));
              }
              catch (Exception ex) {}
              valueWidget = new TextFieldWidget(textFieldSize);
            }
                        ((TextFieldWidget) valueWidget).setPlaceholder(parameters.get("placeholder"));
                    } else {
            if ("radio".equals(parameters.get("style"))) {
              valueWidget = new RadioButtonsWidget();
              if (answerSeparator != null) {
                ((RadioButtonsWidget) valueWidget).setAnswerSeparator(answerSeparator);
                            }
            } else { // dropdown
              valueWidget =buildDropdownWidget(size);
            }
            // need to make sure we have the initialValue too
            String lookFor = existingObs == null ? null : existingObs.getValueText();
            for (int i = 0; i < textAnswers.size(); ++i) {
              String s = textAnswers.get(i);
              if (lookFor != null && lookFor.equals(s))
                lookFor = null;
              String label = null;
              if (answerLabels != null && i < answerLabels.size()) {
                label = answerLabels.get(i);
              } else {
                label = s;
              }
              ((SingleOptionWidget) valueWidget).addOption(new Option(label, s, false));
            }
            // if lookFor is still non-null, we need to add it directly
            // as an option:
            if (lookFor != null)
              ((SingleOptionWidget) valueWidget).addOption(new Option(lookFor, lookFor, true));
          }
        }

        if (initialValue != null) {
          if (isLocationObs) {
            Location l = HtmlFormEntryUtil.getLocation(initialValue, context);
            if (l == null) {
              throw new RuntimeException("Cannot find Location: " + initialValue);
            }
            valueWidget.setInitialValue(l);
          } else if ("person".equals(parameters.get("style"))) {
            Person p = HtmlFormEntryUtil.getPerson(initialValue);
            if (p == null) {
              throw new RuntimeException("Cannot find Person: " + initialValue);
            }
            valueWidget.setInitialValue(new PersonStub(p));
          } else {
            valueWidget.setInitialValue(initialValue);
          }
        }
      } else if (concept.getDatatype().isCoded()) {
        if (parameters.get("answerConceptIds") != null) {
          try {
            for (StringTokenizer st = new StringTokenizer(parameters.get("answerConceptIds"), ","); st
                    .hasMoreTokens();) {
              Concept c = HtmlFormEntryUtil.getConcept(st.nextToken());
              if (c == null)
                throw new RuntimeException("Cannot find concept " + st.nextToken());
              conceptAnswers.add(c);
            }
          }
          catch (Exception ex) {
            throw new RuntimeException("Error in answer list for concept " + concept.getConceptId() + " ("
                    + ex.toString() + "): " + conceptAnswers);
          }
        } else if (parameters.get("answerClasses") != null && !"autocomplete".equals(parameters.get("style"))) {
          try {
            for (StringTokenizer st = new StringTokenizer(parameters.get("answerClasses"), ","); st
                    .hasMoreTokens();) {
              String className = st.nextToken().trim();
              ConceptClass cc = Context.getConceptService().getConceptClassByName(className);
              if (cc == null) {
                throw new RuntimeException("Cannot find concept class " + className);
              }
              conceptAnswers.addAll(Context.getConceptService().getConceptsByClass(cc));
            }
            Collections.sort(conceptAnswers, conceptNameComparator);
          }
          catch (Exception ex) {
            throw new RuntimeException("Error in answer class list for concept " + concept.getConceptId() + " ("
                    + ex.toString() + "): " + conceptAnswers);
          }
        }
       
        if (answerConcept != null) {
          // if there's also an answer concept specified, this is a single
          // checkbox
          answerLabel = parameters.get("answerLabel");
          if (answerLabel == null) {
            String answerCode = parameters.get("answerCode");
            if (answerCode != null) {
              answerLabel = context.getTranslator().translate(userLocaleStr, answerCode);
            } else {
              answerLabel = answerConcept.getBestName(Context.getLocale()).getName();
            }
          }
          valueWidget = new CheckboxWidget(answerLabel, answerConcept.getConceptId().toString());
          if (existingObsList != null && !existingObsList.isEmpty()) {
            for (int i = 0; i < existingObsList.size(); i++) {
              ((DynamicAutocompleteWidget)valueWidget).addInitialValue(existingObsList.get(i).getValueCoded());
            }
          } else if (existingObs != null) {
            valueWidget.setInitialValue(existingObs.getValueCoded());
          } else if (defaultValue != null && Mode.ENTER.equals(context.getMode())) {
            Concept initialValue = HtmlFormEntryUtil.getConcept(defaultValue);
            if (initialValue == null) {
              throw new IllegalArgumentException("Invalid default value. Cannot find concept: " + defaultValue);
            }
            if (!answerConcept.equals(initialValue)) {
              throw new IllegalArgumentException("Invalid default value: " + defaultValue
                      + ". The only allowed answer is: " + answerConcept.getId());
            }
            valueWidget.setInitialValue(initialValue);
          }
        } else if ("true".equals(parameters.get("multiple"))) {
          // if this is a select-multi, we need a group of checkboxes
          throw new RuntimeException("Multi-select coded questions are not yet implemented");
        } else {
          // allow selecting one of multiple possible coded values
         
          // if no answers are specified explicitly (by conceptAnswers or conceptClasses), get them from concept.answers.
          if (!parameters.containsKey("answerConceptIds") && !parameters.containsKey("answerClasses") && !parameters.containsKey("answerDrugs")) {
            conceptAnswers = new ArrayList<Concept>();
            for (ConceptAnswer ca : concept.getAnswers(false)) {
              conceptAnswers.add(ca.getAnswerConcept());
            }
            Collections.sort(conceptAnswers, conceptNameComparator);
          }
         
          if ("autocomplete".equals(parameters.get("style"))) {
            List<ConceptClass> cptClasses = new ArrayList<ConceptClass>();
            if (parameters.get("answerClasses") != null) {
              for (StringTokenizer st = new StringTokenizer(parameters.get("answerClasses"), ","); st
                      .hasMoreTokens();) {
                String className = st.nextToken().trim();
                ConceptClass cc = Context.getConceptService().getConceptClassByName(className);
                cptClasses.add(cc);
              }
            }
            if ((conceptAnswers == null || conceptAnswers.isEmpty())
                    && (cptClasses == null || cptClasses.isEmpty())) {
              throw new RuntimeException(
                      "style \"autocomplete\" but there are no possible answers. Looked for answerConcepts and answerClasses attributes, and answers for concept "
                              + concept.getConceptId());
            }
            if ("true".equals(parameters.get("selectMulti"))) {
              valueWidget = new DynamicAutocompleteWidget(conceptAnswers, cptClasses);
                        }
                        else {
                valueWidget = new ConceptSearchAutocompleteWidget(conceptAnswers, cptClasses);
                        }
                    } else if (parameters.get("answerDrugs") != null) {
                        // we support searching through all drugs via AJAX
                        RemoteJsonAutocompleteWidget widget = new RemoteJsonAutocompleteWidget("/" + WebConstants.WEBAPP_NAME + "/module/htmlformentry/drugSearch.form");
                        widget.setValueTemplate("Drug:{{id}}");
                        if (parameters.get("displayTemplate") != null) {
                            widget.setDisplayTemplate(parameters.get("displayTemplate"));
                        } else {
                            widget.setDisplayTemplate("{{name}}");
                        }
                        if (existingObs != null && existingObs.getValueDrug() != null) {
                            widget.setInitialValue(new Option(existingObs.getValueDrug().getName(), existingObs.getValueDrug().getDrugId().toString(), true));
                        }
                        valueWidget = widget;

                    } else {
                  // Show Radio Buttons if specified, otherwise default to Drop
            // Down
            boolean isRadio = "radio".equals(parameters.get("style"));
            if (isRadio) {
              valueWidget = new RadioButtonsWidget();
              if (answerSeparator != null) {
                ((RadioButtonsWidget) valueWidget).setAnswerSeparator(answerSeparator);
                            }
            } else {
              valueWidget = buildDropdownWidget(size);
            }
            for (int i = 0; i < conceptAnswers.size(); ++i) {
              Concept c = conceptAnswers.get(i);
              String label = null;
              if (answerLabels != null && i < answerLabels.size()) {
                label = answerLabels.get(i);
              } else {
                label = c.getBestName(Context.getLocale()).getName();
              }
              ((SingleOptionWidget) valueWidget).addOption(new Option(label, c.getConceptId().toString(),
                      false));
            }
          }
          if (existingObsList != null && !existingObsList.isEmpty()) {
            for (int i = 0; i < existingObsList.size(); i++) {
              ((DynamicAutocompleteWidget)valueWidget).addInitialValue(existingObsList.get(i).getValueCoded());
            }
          }
          if (existingObs != null) {
                        if (existingObs.getValueDrug() != null) {
                            valueWidget.setInitialValue(existingObs.getValueDrug());
                        } else {
                            valueWidget.setInitialValue(existingObs.getValueCoded());
                        }
                    } else if (defaultValue != null && Mode.ENTER.equals(context.getMode())) {
            Concept initialValue = HtmlFormEntryUtil.getConcept(defaultValue);
            if (initialValue == null) {
              throw new IllegalArgumentException("Invalid default value. Cannot find concept: " + defaultValue);
            }
           
            if (!conceptAnswers.contains(initialValue)) {
              String allowedIds = "";
              for (Concept conceptAnswer : conceptAnswers) {
                allowedIds += conceptAnswer.getId() + ", ";
              }
              allowedIds = allowedIds.substring(0, allowedIds.length() - 2);
              throw new IllegalArgumentException("Invalid default value: " + defaultValue
                      + ". The only allowed answers are: " + allowedIds);
            }
            valueWidget.setInitialValue(initialValue);
          }
        }
      } else if (concept.getDatatype().isBoolean()) {
        String noStr = parameters.get("noLabel");
        if (StringUtils.isEmpty(noStr)) {
          noStr = context.getTranslator().translate(userLocaleStr, "general.no");
        }
        String yesStr = parameters.get("yesLabel");
        if (StringUtils.isEmpty(yesStr)) {
          yesStr = context.getTranslator().translate(userLocaleStr, "general.yes");
        }
       
        if ("checkbox".equals(parameters.get("style"))) {
          if (parameters.get("toggle") != null) {
            ToggleWidget toggleWidget = new ToggleWidget(parameters.get("toggle"));
            valueWidget = new CheckboxWidget(valueLabel, parameters.get("value") != null ? parameters.get("value") : "true", toggleWidget.getTargetId(), toggleWidget.isToggleDim());
          } else {
            valueWidget = new CheckboxWidget(valueLabel, parameters.get("value") != null ? parameters.get("value") : "true", parameters.get("toggle"));
          }
          valueLabel = "";
        } else if ("no_yes".equals(parameters.get("style"))) {
          valueWidget = new RadioButtonsWidget();
          ((RadioButtonsWidget) valueWidget).addOption(new Option(noStr, "false", false));
          ((RadioButtonsWidget) valueWidget).addOption(new Option(yesStr, "true", false));
        } else if ("yes_no".equals(parameters.get("style"))) {
          valueWidget = new RadioButtonsWidget();
          ((RadioButtonsWidget) valueWidget).addOption(new Option(yesStr, "true", false));
          ((RadioButtonsWidget) valueWidget).addOption(new Option(noStr, "false", false));
        } else if ("no_yes_dropdown".equals(parameters.get("style"))) {
          valueWidget = new DropdownWidget();
          ((DropdownWidget) valueWidget).addOption(new Option());
          ((DropdownWidget) valueWidget).addOption(new Option(noStr, "false", false));
          ((DropdownWidget) valueWidget).addOption(new Option(yesStr, "true", false));
        } else if ("yes_no_dropdown".equals(parameters.get("style"))) {
          valueWidget = new DropdownWidget();
          ((DropdownWidget) valueWidget).addOption(new Option());
          ((DropdownWidget) valueWidget).addOption(new Option(yesStr, "true", false));
          ((DropdownWidget) valueWidget).addOption(new Option(noStr, "false", false));
        } else {
          throw new RuntimeException("Boolean with style = " + parameters.get("style")
                  + " not yet implemented (concept = " + concept.getConceptId() + ")");
        }
       
View Full Code Here

        }
        if ("radio".equals(parameters.get("style"))) {
            valueWidget = new RadioButtonsWidget();
        } else { // dropdown
            valueWidget = new DropdownWidget();
            ((DropdownWidget) valueWidget).addOption(new Option());
        }
        for (int i = 0; i < concepts.size(); ++i) {
            Concept c = concepts.get(i);
            String label = null;
            if (conceptLabels != null && i < conceptLabels.size()) {
                label = conceptLabels.get(i);
            } else {
                label = c.getBestName(Context.getLocale()).getName();
            }
            ((SingleOptionWidget) valueWidget).addOption(new Option(
                label, c.getConceptId().toString(), false));
        }
        if (existingObs != null) {
            valueWidget.setInitialValue(existingObs.getConcept());
        }
View Full Code Here

            reasonForExitWidget.setInitialValue(initialAnswer.getDisplayString());
        }

        // populating with exit reason answer options
        boolean initialValueIsSet = !(reasonForExitWidget.getInitialValue() == null);
        reasonForExitWidget.addOption(new Option(Context.getMessageSourceService().getMessage("htmlformentry.chooseAReasonForExit"), "", !initialValueIsSet));

        if (reasonExitConcept != null) {
            for (ConceptAnswer conceptAnswer : reasonExitConcept.getAnswers()) {
                Concept answerConcept = conceptAnswer.getAnswerConcept();
                Option answerOption = new Option(answerConcept.getDisplayString(), answerConcept.getId().toString(), answerConcept.equals(initialAnswer));
                reasonForExitWidget.addOption(answerOption);
            }
        }

        // set the cause for the death and reason for death fields if the reason for the patient's exit is, that the
        // patient has died
        String causeOfDeathConId = Context.getAdministrationService().getGlobalProperty("concept.causeOfDeath");
        Concept causeOfDeathConcept = Context.getConceptService().getConcept(causeOfDeathConId);
        List<Obs> obsDeath = Context.getObsService().getObservationsByPersonAndConcept(patient, causeOfDeathConcept);
        Concept initialCauseOfDeath = null;

        if (obsDeath != null && obsDeath.size() == 1) {
            initialCauseOfDeath = obsDeath.get(0).getValueCoded();
            causeOfDeathWidget.setInitialValue(initialCauseOfDeath.getDisplayString());
            if (obsDeath.get(0).getValueText() != null) {
                otherReasonWidget.setInitialValue(obsDeath.get(0).getValueText());
            }
        }

        // populating with cause of death answer options
        boolean causeOfDeathIsSet = !(causeOfDeathWidget.getInitialValue() == null);
        causeOfDeathWidget.addOption(new Option(Context.getMessageSourceService().getMessage("htmlformentry.chooseACauseToDeath"), "", !causeOfDeathIsSet));

        if (causeOfDeathConcept != null) {
            for (ConceptAnswer conceptAnswer : causeOfDeathConcept.getAnswers()) {
                Concept answerConcept = conceptAnswer.getAnswerConcept();
                Option answerOption = new Option(answerConcept.getDisplayString(), answerConcept.getId().toString(), answerConcept.equals(initialCauseOfDeath));
                causeOfDeathWidget.addOption(answerOption);
            }
        }

        context.registerWidget(dateWidget);
View Full Code Here

      widget = new CheckboxWidget(state.getKey(), state.getValue().getUuid());
    } else {
      SingleOptionWidget singleOption;
      if (tagParams.getType().equals("dropdown")) {
        singleOption = new DropdownWidget();
        singleOption.addOption(new Option("", "", false));
      } else {
        singleOption = new RadioButtonsWidget();
      }
     
      for (Entry<String, ProgramWorkflowState> state : states.entrySet()) {
        boolean select = state.getValue().equals(currentState);
        singleOption.addOption(new Option(state.getKey(), state.getValue().getUuid(), select));
      }
     
      widget = singleOption;
    }
   
View Full Code Here

    String regimenCodes = parameters.get(STANDARD_REGIMEN_CODES);   
    if (regimenCodes == null || regimenCodes.length() < 1)
      throw new IllegalArgumentException("You must provide a valid regimenCode from your standard regimen XML (see global property " + STANDARD_REGIMEN_GLOBAL_PROPERTY + " for these codes) " + parameters);
   
    List<Option> options = new ArrayList<Option>();
    options.add(new Option("", "", false));
   
    StringTokenizer tokenizer = new StringTokenizer(regimenCodes, ",");
    allSystemStandardRegimens = DrugOrderSupport.getInstance().getStandardRegimens();
    StandardRegimenField srf = new StandardRegimenField();
    while (tokenizer.hasMoreElements()) {
      String regCode = (String) tokenizer.nextElement();
      RegimenSuggestion rs = getRegimenSuggestionByCode(regCode, allSystemStandardRegimens);
      if (rs != null){
        options.add(new Option(rs.getDisplayName(),rs.getCodeName(), false));
        srf.addStandardRegimenAnswer(new StandardRegimenAnswer(rs));
        possibleRegimens.add(rs);
      } else {
        throw new IllegalArgumentException("standardRegimen tag can't find regimen code " + regCode + " found in regimenCodes attribute in global property " + STANDARD_REGIMEN_GLOBAL_PROPERTY);
      }
    } 
    DropdownWidget dw = new DropdownWidget();
        dw.setOptions(options);
        regWidget = dw;
        context.registerWidget(regWidget);
        regErrorWidget = new ErrorWidget();
        context.registerErrorWidget(regWidget, regErrorWidget);
       
        //start date
        startDateWidget = new DateWidget();
        startDateErrorWidget = new ErrorWidget();
        context.registerWidget(startDateWidget);
        context.registerErrorWidget(startDateWidget, startDateErrorWidget);
       
        //end date
        discontinuedDateWidget = new DateWidget();
    discontinuedDateErrorWidget = new ErrorWidget();
    context.registerWidget(discontinuedDateWidget);
    context.registerErrorWidget(discontinuedDateWidget, discontinuedDateErrorWidget);
   
    //discontinue reasons
    if (parameters.get(FIELD_DISCONTINUED_REASON) != null){
        String discReasonConceptStr = (String) parameters.get(FIELD_DISCONTINUED_REASON);
        Concept discontineReasonConcept = HtmlFormEntryUtil.getConcept(discReasonConceptStr);
        if (discontineReasonConcept == null)
            throw new IllegalArgumentException("discontinuedReasonConceptId is not set to a valid conceptId or concept UUID");
        srf.setDiscontinuedReasonQuestion(discontineReasonConcept);
       
        discontinuedReasonWidget = new DropdownWidget();
        discontinuedReasonErrorWidget = new ErrorWidget();
       
        List<Option> discOptions = new ArrayList<Option>();
        discOptions.add(new Option("", "", false));
       
        if (parameters.get(FIELD_DISCONTINUED_REASON_ANSWERS) != null){
            //setup a list of the reason concepts
            List<Concept> discReasons = new ArrayList<Concept>();
            String discAnswersString = (String) parameters.get(FIELD_DISCONTINUED_REASON_ANSWERS);
            String[] strDiscAnswers = discAnswersString.split(",");
            for (int i = 0; i < strDiscAnswers.length; i++){
                String thisAnswer = strDiscAnswers[i];
                Concept answer = HtmlFormEntryUtil.getConcept(thisAnswer, "discontinueReasonAnswers includes a value that is not a valid conceptId or concept UUID");
                  discReasons.add(answer);
            }
          
            if (parameters.get(FIELD_DISCONTINUED_REASON_ANSWER_LABELS) != null){
                // use the listed discontinueReasons, and use labels:
                String discLabelsString = parameters.get(FIELD_DISCONTINUED_REASON_ANSWER_LABELS);
                String[] strDiscAnswerLabels = discLabelsString.split(",");
                //a little validation:
                if (strDiscAnswerLabels.length != discReasons.size())
                    throw new RuntimeException("discontinueReasonAnswers and discontinueReasonAnswerLabels must contain the same number of members.");
                for (int i = 0; i < strDiscAnswerLabels.length; i ++ ){
                    discOptions.add(new Option( strDiscAnswerLabels[i], discReasons.get(i).getConceptId().toString(),false))
                    srf.addDiscontinuedReasonAnswer(new ObsFieldAnswer(strDiscAnswerLabels[i].trim(), discReasons.get(i)));
                }
            } else {
                // use the listed discontinueReasons, and use their ConceptNames.
                for (Concept c: discReasons){
                    discOptions.add(new Option( c.getBestName(Context.getLocale()).getName(), c.getConceptId().toString(),false));
                    srf.addDiscontinuedReasonAnswer(new ObsFieldAnswer(c.getBestName(Context.getLocale()).getName(), c));
                }
            }
        } else {
            //just use the conceptAnswers
            for (ConceptAnswer ca : discontineReasonConcept.getAnswers()){
                discOptions.add(new Option( ca.getAnswerConcept().getBestName(Context.getLocale()).getName(), ca.getAnswerConcept().getConceptId().toString(),false));
                srf.addDiscontinuedReasonAnswer(new ObsFieldAnswer(ca.getAnswerConcept().getBestName(Context.getLocale()).getName(), ca.getAnswerConcept()));
            }
        }
        if (discOptions.size() == 1)
            throw new IllegalArgumentException("discontinue reason Concept doesn't have any ConceptAnswers");
View Full Code Here

TOP

Related Classes of org.openmrs.module.htmlformentry.widget.Option

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.