List of usage examples for org.apache.wicket.markup.html.list ListView setReuseItems
public ListView<T> setReuseItems(boolean reuseItems)
From source file:de.alpharogroup.wicket.components.form.checkbox.CheckGroupSelectorPanel.java
License:Apache License
/** * Factory method for creating the new {@link ListView} for the choices. This method is invoked * in the constructor from the derived classes and can be overridden so users can provide their * own version of the new {@link ListView} for the choices. * * @param id/* w w w . j a va2 s . c o m*/ * the id * @param model * the model * @return the new {@link ListView} for the choices. */ protected ListView<T> newChoices(final String id, final IModel<CheckboxModelBean<T>> model) { final ListView<T> choices = new ListView<T>("choices", model.getObject().getChoices()) { /** The serialVersionUID. */ private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override protected void populateItem(final ListItem<T> item) { item.add(new Check<>("checkbox", item.getModel())); item.add(new Label("label", new PropertyModel<String>(item.getDefaultModel(), model.getObject().getLabelPropertyExpression()))); } }; choices.setReuseItems(true); return choices; }
From source file:de.alpharogroup.wicket.components.i18n.list.SpanListPanel.java
License:Apache License
/** * {@inheritDoc}//from w w w.ja v a 2 s.c o m */ @Override protected ListView<T> newListView(final String id, final IModel<List<T>> model) { final ListView<T> listView = new ListView<T>(id, model) { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override protected void onComponentTag(final ComponentTag tag) { super.onComponentTag(tag); // Turn the div tag to a span tag.setName("span"); } /** * {@inheritDoc} */ @Override protected void populateItem(final ListItem<T> item) { item.add(newListComponent("item", item)); } }; listView.setReuseItems(true); return listView; }
From source file:de.alpharogroup.wicket.components.listview.ListViewPanel.java
License:Apache License
/** * Factory method for creating a new {@link ListView}. This method is invoked in the constructor * from the derived classes and can be overridden so users can provide their own version of the * new {@link ListView}./*ww w . ja va 2 s. c o m*/ * * @param id * the id * @param model * the model * @return the new {@link ListView}. */ protected ListView<T> newListView(final String id, final IModel<List<T>> model) { final ListView<T> listView = new ListView<T>(id, model) { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override protected void populateItem(final ListItem<T> item) { item.add(newListComponent("item", item)); } }; listView.setReuseItems(true); return listView; }
From source file:gr.abiss.calipso.wicket.CustomFieldsFormPanel.java
License:Open Source License
@SuppressWarnings("serial") private void addComponents(final CompoundPropertyModel model, final Metadata metadata, final List<Field> fields, final Map<String, FileUploadField> fileUploadFields) { //final AbstractItem item = (AbstractItem) model.getObject(); List<FieldGroup> fieldGroupsList = metadata.getFieldGroups(); @SuppressWarnings("unchecked") ListView fieldGroups = new ListView("fieldGroups", fieldGroupsList) { @Override// ww w. j ava 2s . c o m protected void populateItem(ListItem listItem) { FieldGroup fieldGroup = (FieldGroup) listItem.getModelObject(); listItem.add(new Label("fieldGroupLabel", fieldGroup.getName())); List<Field> groupFields = fieldGroup.getFields(); List<Field> editableGroupFields = new LinkedList<Field>(); if (CollectionUtils.isNotEmpty(groupFields)) { for (Field field : groupFields) { // is editable? if (fields.contains(field)) { editableGroupFields.add(field); } } } ListView listView = new ListView("fields", editableGroupFields) { @Override @SuppressWarnings("deprecation") protected void populateItem(ListItem listItem) { boolean preloadExistingValue = true; final Field field = (Field) listItem.getModelObject(); // preload custom attribute if (field.getCustomAttribute() == null) { field.setCustomAttribute(getCalipso().loadItemCustomAttribute(getCurrentSpace(), field.getName().getText())); } // preload value? if (preloadExistingValue) { AbstractItem history = (AbstractItem) model.getObject(); history.setValue(field.getName(), item.getValue(field.getName())); } // return the value for the field (see abstract item getCustomValue method) Object fieldLastCustomValue = null; String i18nedFieldLabelResourceKey = item.getSpace() .getPropertyTranslationResourceKey(field.getName().getText()); if (item != null && !editMode) { if (field.getName().isFile()) { Set<Attachment> tmpAttachments = item.getAttachments(); if (tmpAttachments != null && tmpAttachments.size() > 0) { for (Attachment attachment : tmpAttachments) { if (field.getLabel() .equals(AttachmentUtils.getBaseName(attachment.getFileName()))) { fieldLastCustomValue = attachment.getFileName(); break; } } } } else { fieldLastCustomValue = item.getValue(field.getName()); } } // Decide whether the field is mandatory boolean valueRequired = false; //logger.info("fieldLastCustomValue for field " + field.getLabel() +": "+fieldLastCustomValue); if (field.getMask() == State.MASK_MANDATORY || (field.getMask() == State.MASK_MANDATORY_IF_EMPTY && (fieldLastCustomValue == null || StringUtils.isBlank(fieldLastCustomValue.toString())))) { valueRequired = true; // value required } // go over custom fields WebMarkupContainer labelContainer = new WebMarkupContainer("labelContainer"); listItem.add(labelContainer); SimpleFormComponentLabel label = null; if (field.getName().isDropDownType()) { String autoValue; final Map<String, String> options = field.getOptions(); if (field.getFieldType().equals(Field.FIELD_TYPE_DROPDOWN_HIERARCHICAL)) { Fragment f = new Fragment("field", "treeField", CustomFieldsFormPanel.this); // add HTML description through velocity addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription", field.getCustomAttribute().getHtmlDescription(), null, true); ItemFieldCustomAttribute customAttribute = field.getCustomAttribute(); // if(customAttribute == null){ // customAttribute = getCalipso().loadCustomAttribute(getCurrentSpace(), field.getName().getText()); // field.setCustomAttribute(customAttribute); // } // preload existing value if (field.getCustomAttribute() != null && customAttribute.getLookupValue() == null && item.getCustomValue(field) != null) { logger.info("preloading custom attribute for field: " + field.getLabel()); customAttribute.setLookupValue(getCalipso().loadCustomAttributeLookupValue( NumberUtils.createLong(item.getCustomValue(field).toString()))); customAttribute.setAllowedLookupValues( getCalipso().findActiveLookupValuesByCustomAttribute(customAttribute)); } else { logger.info( "SKIPPED preloading custom attribute for field: " + field.getLabel()); customAttribute.setAllowedLookupValues( getCalipso().findActiveLookupValuesByCustomAttribute(customAttribute)); } TreeChoice choice = new TreeChoice("field", new PropertyModel<CustomAttributeLookupValue>(field, "customAttribute.lookupValue"), customAttribute.getAllowedLookupValues(), customAttribute); // TODO: temp, make configurable in space field form for 1520 int attrId = customAttribute.getId().intValue(); choice.setVisibleMenuLinks( attrId == 3 || attrId == 4 || attrId == 16 || attrId == 17); //choice.setType(Long.class); choice.setRequired(valueRequired); // i18n choice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey)); WebMarkupContainer border = new WebMarkupContainer("border"); f.add(border); //border.add(new ErrorHighlighter(choice)); border.add(choice); //choice.setModel(model.bind(field.getName().getText())); //border.add(model.bind(choice, field.getName().getText())); listItem.add(f.setRenderBodyOnly(true)); label = new SimpleFormComponentLabel("label", choice); } // get the type of component that will render the choices else if (field.getFieldType().equals(Field.FIELD_TYPE_AUTOSUGGEST)) { renderAutoSuggest(model, listItem, field, i18nedFieldLabelResourceKey, valueRequired, options); } else { // normal drop down label = renderDropDown(model, listItem, field, i18nedFieldLabelResourceKey, valueRequired, options); } } else if (field.getName().equals(Field.Name.ASSIGNABLE_SPACES)) { Fragment f = new Fragment("field", "dropDown", CustomFieldsFormPanel.this); // add HTML description through velocity addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription", field.getCustomAttribute().getHtmlDescription(), null, true); List assignableSpaces = loadAssignableSpaces(field); final Map options = new LinkedHashMap(); // Replace value from space id to space description for // reasons of appearance. for (int i = 0; i < assignableSpaces.size(); i++) { Space space = (Space) assignableSpaces.get(i); if (!space.equals(getCurrentSpace())) { options.put(space.getId(), localize(space.getNameTranslationResourceKey())); } // if } // for final List keys = new ArrayList(options.keySet()); AssignableSpacesDropDownChoice choice = new AssignableSpacesDropDownChoice("field", keys, new IChoiceRenderer() { @Override public Object getDisplayValue(Object o) { return o; }; @Override public String getIdValue(Object o, int i) { return o.toString(); }; }); choice.setNullValid(true); // i18n choice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey)); choice.setRequired(valueRequired); choice.add(new Behavior() { @Override public void renderHead(Component component, IHeaderResponse response) { response.renderJavaScript(new JavaScripts().setAssignableSpacesId.asString(), "setAssignableSpacesId"); } }); choice.add(new AjaxFormComponentUpdatingBehavior("onChange") { @Override protected void onUpdate(AjaxRequestTarget target) { if (statusChoice != null && !statusChoice.getDefaultModelObjectAsString().equals("") && !statusChoice.getDefaultModelObjectAsString().equals("-1")) { // if // (statusChoice.getValue().equals(String.valueOf(State.MOVE_TO_OTHER_SPACE))){ // assignedToChoice.setChoices(getAssignableSpaceUsers()); // assignedToChoice.setNullValid(false); // assignedToChoice.setVisible(true); // }//if } // if target.appendJavaScript("assignableSpacesId=" + "'" + assignableSpacesDropDownChoice.getMarkupId() + "';"); // This can happen at the creation of a new item // where makes no sense to be moved to other space if (assignedToChoice != null) { target.addComponent(assignedToChoice); } }// onUpdate @Override protected void onError(AjaxRequestTarget arg0, RuntimeException arg1) { // Do nothing. // It happens only if the choice be set to NULL by // the user. // The exception occurs because the model binds to // space id that is from (primitive) type // long and its value can not be set to NULL. } }); choice.setOutputMarkupId(true); assignableSpacesDropDownChoice = choice; if (itemViewFormPanel != null) { itemViewFormPanel.getItemViewForm() .setAssignableSpacesDropDownChoice(assignableSpacesDropDownChoice); } // if WebMarkupContainer border = new WebMarkupContainer("border"); f.add(border); border.add(new ErrorHighlighter(choice)); // Set field name explicitly to avoid runtime error //border.add(model.bind(choice, field.getName() + ".id")); choice.setModel(model.bind(field.getName() + ".id")); border.add(choice); listItem.add(f.setRenderBodyOnly(true)); border.setVisible(!CustomFieldsFormPanel.this.editMode); label = new SimpleFormComponentLabel("label", choice); } else if (field.getName().getType() == 6) { // date picker Fragment fragment = new Fragment("field", "dateFragment", CustomFieldsFormPanel.this); // add HTML description through velocity addVelocityTemplatePanel(fragment, "htmlDescriptionContainer", "htmlDescription", field.getCustomAttribute().getHtmlDescription(), null, true); if (item.getId() == 0 && item.getValue(field.getName()) == null && field.getDefaultValueExpression() != null && field.getDefaultValueExpression().equalsIgnoreCase("now")) { item.setValue(field.getName(), new Date()); } DateField calendar = new DateField("field", preloadExistingValue ? new PropertyModel(model.getObject(), field.getName().getText()) : new PropertyModel(model, field.getName().getText())) { @Override protected String getDateFormat() { // TODO Auto-generated method stub return metadata.getDateFormats().get(Metadata.DATE_FORMAT_SHORT); } }; calendar.setRequired(valueRequired); // i8n calendar.setLabel(new ResourceModel(i18nedFieldLabelResourceKey)); fragment.add(calendar); listItem.add(fragment.setRenderBodyOnly(true)); label = new SimpleFormComponentLabel("label", calendar); } // TODO: Creating new space item - users custom field else if (field.getName().isOrganization()) { // is organization // Get users list Fragment f = new Fragment("field", "dropDownFragment", CustomFieldsFormPanel.this); // add HTML description through velocity addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription", field.getCustomAttribute().getHtmlDescription(), null, true); Organization organization = (Organization) item.getValue(field.getName()); // logger.debug("Item organization field has value: "+organization); final List<Organization> allOrganizationsList = getCalipso().findAllOrganizations(); DropDownChoice organizationChoice = new DropDownChoice("field", allOrganizationsList, new IChoiceRenderer() { // user's choice renderer // display value user's name @Override public Object getDisplayValue(Object object) { return ((Organization) object).getName(); } @Override public String getIdValue(Object object, int index) { // id value user's id return index + ""; } }); organizationChoice.add(new ErrorHighlighter()); organizationChoice.setRequired(valueRequired); // i18n organizationChoice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey)); //f.add(model.bind(organizationChoice, field.getName().getText())); organizationChoice.setModel(model.bind(field.getName().getText())); f.add(organizationChoice); listItem.add(f.setRenderBodyOnly(true)); label = new SimpleFormComponentLabel("label", organizationChoice); } else if (field.getName().isFile()) { // File addFileInputField(model, fileUploadFields, listItem, field, i18nedFieldLabelResourceKey, valueRequired); } // TODO: Creating new space item - organizations custom field else if (field.getName().isUser()) { // is user Fragment f = new Fragment("field", "dropDownFragment", CustomFieldsFormPanel.this); // add HTML description through velocity addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription", field.getCustomAttribute().getHtmlDescription(), null, true); // find organization id from field's options String strOrgId = field.getOptions().get("organizationId"); Long orgId = Long.valueOf(strOrgId); // load organization from database Organization selectedOrg = getCalipso().loadOrganization(orgId); // TODO: load all users from organization // add new list of selected organizations List<Organization> selectedOrganization = new ArrayList<Organization>(); // add selected organization selectedOrganization.add(selectedOrg); final List<User> usersFromOrganization = getCalipso() .findUsersInOrganizations(selectedOrganization); // TODO: dropdown of all organization DropDownChoice usersFromOrganizationChoice = new DropDownChoice("field", usersFromOrganization, new UserChoiceRenderer()); usersFromOrganizationChoice.setNullValid(false); usersFromOrganizationChoice.setRequired(valueRequired); // i18n usersFromOrganizationChoice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey)); //f.add(model.bind(usersFromOrganizationChoice, field.getName().getText())); usersFromOrganizationChoice.setModel(model.bind(field.getName().getText())); f.add(usersFromOrganizationChoice); listItem.add(f.setRenderBodyOnly(true)); label = new SimpleFormComponentLabel("label", usersFromOrganizationChoice); } else if (field.getName().isCountry()) { // organization fragment holds a dropDown of countries final List<Country> allCountriesList = getCalipso().findAllCountries(); Fragment f = new Fragment("field", "dropDownFragment", CustomFieldsFormPanel.this); // add HTML description through velocity addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription", field.getCustomAttribute().getHtmlDescription(), null, true); listItem.add(f.setRenderBodyOnly(true)); DropDownChoice countryChoice = getCountriesDropDown("field", allCountriesList); countryChoice.add(new ErrorHighlighter()); countryChoice.setRequired(valueRequired); // i18n countryChoice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey)); //f.add(model.bind(countryChoice, field.getName().getText())); countryChoice.setModel(model.bind(field.getName().getText())); f.add(countryChoice); label = new SimpleFormComponentLabel("label", countryChoice); } else { if (logger.isDebugEnabled()) logger.debug("model.getObject(): " + model.getObject()); if (logger.isDebugEnabled()) logger.debug( "model.getObject().getClass(): " + model.getObject().getClass().getName()); if (logger.isDebugEnabled()) logger.debug("field.getName().getText(): " + field.getName().getText()); //if(logger.isDebugEnabled()) logger.debug("((Item)model.getObject()).getCusStr01(): "+((Item)model.getObject()).getCusStr01()); FormComponent textField; Fragment f; if (field.isMultivalue()) { f = new Fragment("field", "multipleValuesTextField", CustomFieldsFormPanel.this); // add HTML description through velocity addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription", field.getCustomAttribute().getHtmlDescription(), null, true); if (logger.isDebugEnabled()) logger.debug("model.getObject(): " + model.getObject()); if (logger.isDebugEnabled()) logger.debug("field.getName().getText(): " + field.getName().getText()); textField = preloadExistingValue ? new MultipleValuesTextField("field", new PropertyModel(model.getObject(), field.getName().getText()), field.getXmlConfig()) : new MultipleValuesTextField("field", field.getXmlConfig()); } else if (field.getLineCount() == 1) { f = new Fragment("field", "textField", CustomFieldsFormPanel.this); // add HTML description through velocity addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription", field.getCustomAttribute().getHtmlDescription(), null, true); textField = preloadExistingValue ? new TextField("field", new PropertyModel(model.getObject(), field.getName().getText())) : new TextField("field"); } else { f = new Fragment("field", "textareaField", CustomFieldsFormPanel.this); // add HTML description through velocity addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription", field.getCustomAttribute().getHtmlDescription(), null, true); textField = preloadExistingValue ? new TextArea("field", new PropertyModel(model.getObject(), field.getName().getText())) { @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); tag.put("rows", field.getLineCount().toString()); } } : new TextArea("field") { @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); tag.put("rows", field.getLineCount().toString()); } }; } // any validations for this field? ValidationExpression validationExpression = getCalipso() .loadValidationExpression(field.getValidationExpressionId()); if (validationExpression != null) { textField.add(new ValidationExpressionValidator(validationExpression)); } // TODO: do we need these two? if (field.getName().getType() == 4) { textField.setType(Double.class); } else if (field.getName().isDecimalNumber()) { textField.add(new PositiveNumberValidator()); } textField.add(new ErrorHighlighter()); textField.setRequired(valueRequired); // i18n textField.setLabel(new ResourceModel(i18nedFieldLabelResourceKey)); if (preloadExistingValue) { f.add(textField); } else { //f.add(model.bind(textField, field.getName().getText())); textField.setModel(model.bind(field.getName().getText())); f.add(textField); } // f.add(textField); listItem.add(f.setRenderBodyOnly(true)); label = new SimpleFormComponentLabel("label", textField); // styles FieldUtils.appendFieldStyles(field.getXmlConfig(), textField); } // add label labelContainer.add(label != null ? label : new Label("label", "")); if (field.getCustomAttribute() != null && StringUtils.isBlank(field.getCustomAttribute().getHtmlDescription())) { labelContainer.add(new SimpleAttributeModifier("class", "labelContainer")); } // mandatory? // mark as mandatory in the UI? labelContainer .add(new Label("star", valueRequired ? "* " : " ").setEscapeModelStrings(false)); } private SimpleFormComponentLabel renderAutoSuggest(final IModel model, ListItem listItem, final Field field, String i18nedFieldLabelResourceKey, boolean valueRequired, final Map<String, String> options) { SimpleFormComponentLabel label = null; Fragment f = new Fragment("field", "autoCompleteFragment", CustomFieldsFormPanel.this); // add HTML description through velocity addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription", field.getCustomAttribute().getHtmlDescription(), null, true); final List<String> autoKeys = new ArrayList<String>( options != null ? new ArrayList<String>(options.keySet()) : new ArrayList<String>()); // the autocomplet textField // TODO: fix to render values instead of integer AbstractAutoCompleteRenderer autoRenderer = new AbstractAutoCompleteRenderer() { @Override protected String getTextValue(Object object) { // TODO Auto-generated method stub return object.toString(); } @Override protected void renderChoice(Object object, Response response, String criteria) { response.write(object.toString()); } }; autoTextField = new AutoCompleteTextField("field", new PropertyModel(field, "customAttribute.lookupValue")) { // TODO: the list @Override protected Iterator<String> getChoices(String input) { if (Strings.isEmpty(input)) { List<String> emptyList = Collections.emptyList(); return emptyList.iterator(); } List<String> searchResults = new ArrayList<String>(); for (String s : options.values()) { if (s.startsWith(input)) { searchResults.add(s); } } return searchResults.iterator(); } }; autoTextField.add(new AjaxFormComponentUpdatingBehavior("onchange") { @Override protected void onUpdate(AjaxRequestTarget target) { // TODO Auto-generated method stub List<String> searchResults = new ArrayList<String>(); for (String s : options.values()) { if (s.startsWith((String) autoTextField.getModelObject())) { searchResults.add(s); } } target.addComponent(autoTextField); } }); // i18n autoTextField.setLabel(new ResourceModel(i18nedFieldLabelResourceKey)); String componentValue = (String) ((autoTextField != null && autoTextField.getModelObject() != null) ? autoTextField.getModelObject() : null); autoTextField.setRequired(valueRequired); WebMarkupContainer border = new WebMarkupContainer("border"); f.add(border); border.add(new ErrorHighlighter(autoTextField)); autoTextField.setModel(new PropertyModel(model.getObject(), field.getName().getText())); //border.add(model.bind(autoTextField, field.getName().getText())); border.add(autoTextField); if (logger.isDebugEnabled() && autoTextField != null && autoTextField.getDefaultModelObjectAsString() != null) { if (logger.isDebugEnabled()) logger.debug( "Auto complete value is :" + autoTextField.getDefaultModelObjectAsString()); } listItem.add(f.setRenderBodyOnly(true)); label = new SimpleFormComponentLabel("label", autoTextField); return label; // ------------------------- } private SimpleFormComponentLabel addFileInputField(final CompoundPropertyModel model, final Map<String, FileUploadField> fileUploadFields, ListItem listItem, final Field field, String i18nedFieldLabelResourceKey, boolean valueRequired) { SimpleFormComponentLabel label = null; Fragment f = new Fragment("field", "fileField", CustomFieldsFormPanel.this); // add HTML description through velocity addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription", field.getCustomAttribute().getHtmlDescription(), null, true); FileUploadField fileField = new FileUploadField("field"); fileUploadFields.put(field.getLabel(), fileField); fileField.add(new ErrorHighlighter()); fileField.setRequired(valueRequired); // i18n fileField.setLabel(new ResourceModel( StringUtils.isNotBlank(i18nedFieldLabelResourceKey) ? i18nedFieldLabelResourceKey : Field.FIELD_TYPE_SIMPLE_ATTACHEMENT));//field.getName().getText().equalsIgnoreCase(Field.FIELD_TYPE_SIMPLE_ATTACHEMENT) ? Field.FIELD_TYPE_SIMPLE_ATTACHEMENT : i18nedFieldLabelResourceKey)); //f.add(model.bind(fileField, field.getName().getText())); fileField.setModel(new Model()); // List<FileUpload> fileUploads = new LinkedList<FileUpload>(); f.add(fileField); listItem.add(f.setRenderBodyOnly(true)); label = new SimpleFormComponentLabel("label", fileField); return label; } /** * @param model * @param listItem * @param field * @param i18nedFieldLabelResourceKey * @param valueRequired * @param options */ private SimpleFormComponentLabel renderDropDown(final IModel model, ListItem listItem, final Field field, String i18nedFieldLabelResourceKey, boolean valueRequired, final Map<String, String> options) { SimpleFormComponentLabel label = null; /* final List<CustomAttributeLookupValue> lookupValues = getCalipso().findLookupValuesByCustomAttribute(field.getCustomAttribute()); TreeChoice choice = new TreeChoice("field", new PropertyModel(field, "customAttribute.lookupValue"), lookupValues); choice.setType(CustomAttributeLookupValue.class); //choice.setType(Long.class); choice.setRequired(valueRequired); // i18n choice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey)); WebMarkupContainer border = new WebMarkupContainer("border"); f.add(border); //border.add(new ErrorHighlighter(choice)); border.add(choice); */ // drop down list final Fragment fragment = new Fragment("field", "dropDown", CustomFieldsFormPanel.this); if (field.getCustomAttribute() == null) { field.setCustomAttribute(getCalipso().loadItemCustomAttribute(getCurrentSpace(), field.getName().getText())); } // add HTML description through velocity logger.info("field name:" + field.getName() + ", custom atribute: " + field.getCustomAttribute()); addVelocityTemplatePanel(fragment, "htmlDescriptionContainer", "htmlDescription", field.getCustomAttribute() != null ? field.getCustomAttribute().getHtmlDescription() : "", null, true); final List<CustomAttributeLookupValue> lookupValues = getCalipso() .findActiveLookupValuesByCustomAttribute(field.getCustomAttribute()); // preselect previous user choice from DB if available Object preselected = item.getValue(field.getName()); if (preselected != null) { String sPreselectedId = preselected.toString(); if (CollectionUtils.isNotEmpty(lookupValues)) { for (CustomAttributeLookupValue value : lookupValues) { if ((value.getId() + "").equals(sPreselectedId)) { field.getCustomAttribute().setLookupValue(value); break; } } } } // else set using the default string value instead, if any // TODO: move this into a LookupValueDropDownChoice class else { String defaultStringValue = field.getCustomAttribute() != null ? field.getCustomAttribute().getDefaultStringValue() : null; if (defaultStringValue != null && CollectionUtils.isNotEmpty(lookupValues)) { for (CustomAttributeLookupValue value : lookupValues) { if (value.getValue().equals(defaultStringValue)) { field.getCustomAttribute().setLookupValue(value); break; } } } } DropDownChoice choice = new DropDownChoice("field", new PropertyModel(field, "customAttribute.lookupValue"), lookupValues, new IChoiceRenderer<CustomAttributeLookupValue>() { @Override public Object getDisplayValue(CustomAttributeLookupValue o) { return fragment.getString(o.getNameTranslationResourceKey()); } @Override public String getIdValue(CustomAttributeLookupValue o, int index) { return String.valueOf(index); } }); choice.setNullValid(true); // i18n choice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey)); choice.setRequired(valueRequired); WebMarkupContainer border = new WebMarkupContainer("border"); fragment.add(border); border.add(new ErrorHighlighter(choice)); //border.add(model.bind(choice, field.getName().getText())); border.add(choice); listItem.add(fragment.setRenderBodyOnly(true)); label = new SimpleFormComponentLabel("label", choice); return label; } /** * @param model * @param listItem * @param field * @param i18nedFieldLabelResourceKey * @param valueRequired * @param options */ private SimpleFormComponentLabel renderPeriodPartDropDown(final CompoundPropertyModel model, ListItem listItem, final Field field, String i18nedFieldLabelResourceKey, boolean valueRequired, final List<Date> options) { SimpleFormComponentLabel label = null; // drop down list Fragment f = new Fragment("field", "dropDown", CustomFieldsFormPanel.this); // add HTML description through velocity addVelocityTemplatePanel(f, "htmlDescriptionContainer", "htmlDescription", field.getCustomAttribute().getHtmlDescription(), null, true); DropDownChoice choice = new DropDownChoice("field", options, new IChoiceRenderer() { @Override public Object getDisplayValue(Object o) { return DateUtils.format((Date) o); }; @Override public String getIdValue(Object o, int i) { return String.valueOf(i); }; }); choice.setNullValid(true); // i18n choice.setLabel(new ResourceModel(i18nedFieldLabelResourceKey)); choice.setRequired(valueRequired); WebMarkupContainer border = new WebMarkupContainer("border"); f.add(border); border.add(new ErrorHighlighter(choice)); //border.add(model.bind(choice, field.getName().getText())); choice.setModel(model.bind(field.getName().getText())); border.add(choice); listItem.add(f.setRenderBodyOnly(true)); label = new SimpleFormComponentLabel("label", choice); return label; } }; if (editableGroupFields.isEmpty()) { listItem.setVisible(false); } listView.setReuseItems(true); listItem.add(listView.setRenderBodyOnly(true)); } }; add(fieldGroups.setReuseItems(true)); // }
From source file:gr.abiss.calipso.wicket.ItemView.java
License:Open Source License
private void addComponents(ItemRenderingTemplate tmpl, final Item item) { //Edit item is only possible for "global" administrator and current space administrator User currentUser = getPrincipal();// w w w . ja v a 2s. com Space currentSpace = getCurrentSpace(); if (tmpl != null && tmpl.getShowSpaceName()) { add(new Label("title", this.localize(currentSpace))); } else { add(new Label("title", "").setVisible(false)); } WebMarkupContainer editContainer = new WebMarkupContainer("editContainer"); add(editContainer.setRenderBodyOnly(true)); editContainer.add(new Link("edit") { @Override public void onClick() { //breadcrum must be activated in the active panel, that is ItemViewPanel ((BreadCrumbPanel) getBreadCrumbModel().getActive()).activate(new IBreadCrumbPanelFactory() { @Override public BreadCrumbPanel create(String componentId, IBreadCrumbModel breadCrumbModel) { return new ItemFormPanel(componentId, breadCrumbModel, item.getId()); } }); } }); editContainer.setVisible(currentUser.isGlobalAdmin() || currentUser.isSpaceAdmin(currentSpace)); if (hideLinks) { editContainer.setVisible(false); } add(new Link("printToPdf") { @Override public void onClick() { // TODO: pickup print template from DB if appropriate // TODO: is this needed? //panels that change with navigation //ItemViewPage itemViewPage = new ItemViewPage(refId, null); String markup = "error generating report"; CharSequence resultCharSequence = renderPageHtmlInNewRequestCycle(ItemTemplateViewPage.class, new PageParameters("0=" + item.getUniqueRefId())); markup = resultCharSequence.toString(); if (StringUtils.isNotBlank(markup)) { markup = markup.replaceFirst("../../logo.png", "logo.png").replaceFirst("../logo.png", "logo.png"); } // logger.info("printToPdf: " + markup); getRequestCycle().scheduleRequestHandlerAfterCurrent( new PdfRequestTarget(PdfUtils.getPdf(getCalipso(), item, markup, ItemView.this), item.getRefId())); } }); String refId = item.getUniqueRefId(); Link refIdLink = new BookmarkablePageLink("uniqueRefId", ItemViewPage.class, new PageParameters("0=" + refId)); add(refIdLink.add(new Label("uniqueRefId", refId))); //Relate Link ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ WebMarkupContainer relatedContainer = new WebMarkupContainer("relatedContainer"); add(relatedContainer); RelateLink relateLink1 = new RelateLink("relate1", item, getBreadCrumbModel(), currentUser, ItemView.this); //relateLink1.setVisible(!hideLinks); relatedContainer.add(relateLink1); if (currentUser.hasRegularRoleForSpace(item.getSpace())) { relatedContainer.setVisible(true); } else { relatedContainer.setVisible(false); } if (item.getRelatedItems() != null) { add(new ListView("relatedItems", new ArrayList(item.getRelatedItems())) { @Override protected void populateItem(ListItem listItem) { final ItemItem itemItem = (ItemItem) listItem.getModelObject(); String message = null; if (itemItem.getType() == DUPLICATE_OF) { message = localize("item_view.duplicateOf"); } else if (itemItem.getType() == DEPENDS_ON) { message = localize("item_view.dependsOn"); } else if (itemItem.getType() == RELATED) { message = localize("item_view.relatedTo"); } final String refId = itemItem.getRelatedItem().getUniqueRefId(); if (hideLinks) { message = message + " " + refId; } listItem.add(new Label("message", message)); Link link = new Link("link") { @Override public void onClick() { setResponsePage(ItemViewPage.class, new PageParameters("0=" + refId)); } }; link.add(new Label("refId", refId)); link.setVisible(!hideLinks); listItem.add(link); listItem.add(new Link("remove") { @Override public void onClick() { setResponsePage(new ItemRelateRemovePage(item.getId(), itemItem)); } }.setVisible(!hideLinks)); } }); } else { add(new WebMarkupContainer("relatedItems").setVisible(false)); } if (item.getRelatingItems() != null) { add(new ListView("relatingItems", new ArrayList(item.getRelatingItems())) { @Override protected void populateItem(ListItem listItem) { final ItemItem itemItem = (ItemItem) listItem.getModelObject(); // this looks very similar to related items block above // but the display strings could be different and in future handling of the // inverse of the bidirectional link could be different as well String message = null; if (itemItem.getType() == DUPLICATE_OF) { message = localize("item_view.duplicateOfThis"); } else if (itemItem.getType() == DEPENDS_ON) { message = localize("item_view.dependsOnThis"); } else if (itemItem.getType() == RELATED) { message = localize("item_view.relatedToThis"); } // final String refId = itemItem.getItem().getRefId(); final String refId = itemItem.getItem().getUniqueRefId(); if (hideLinks) { message = refId + " " + message; } listItem.add(new Label("message", message)); Link link = new Link("link") { @Override public void onClick() { setResponsePage(ItemViewPage.class, new PageParameters("0=" + refId)); } }; link.add(new Label("refId", refId)); link.setVisible(!hideLinks); listItem.add(link); listItem.add(new Link("remove") { @Override public void onClick() { setResponsePage(new ItemRelateRemovePage(item.getId(), itemItem)); } }.setVisible(!hideLinks)); } }); } else { add(new WebMarkupContainer("relatingItems").setVisible(false)); } add(new Label("status", new PropertyModel(item, "statusValue"))); //user profile view link add(new UserViewLink("loggedBy", getBreadCrumbModel(), item.getLoggedBy()) .setVisible(!getPrincipal().isAnonymous())); if (item.getAssignedTo() != null) { add(new UserViewLink("assignedTo", getBreadCrumbModel(), item.getAssignedTo()) .setVisible(!getPrincipal().isAnonymous())); } else { Label assignedToLabel = new Label("assignedTo", localize("item.unassigned")); if (item.getStatus() != State.CLOSED) { assignedToLabel.add(new SimpleAttributeModifier("class", "unassigned")); } add(assignedToLabel); } add(new UserViewLink("reportedBy", getBreadCrumbModel(), item.getReportedBy())); WebMarkupContainer summaryContainer = new WebMarkupContainer("summaryContainer"); summaryContainer.add(new Label("summary", new PropertyModel(item, "summary"))); add(summaryContainer.setVisible(item.getSpace().isItemSummaryEnabled())); //detail commented out //add(new Label("detail", new PropertyModel(item, "detail")).setEscapeModelStrings(false)); final SimpleAttributeModifier sam = new SimpleAttributeModifier("class", "alt"); // All custom fields of the fields that belong to the item and are viewable for // the session user final Map<Field.Name, Field> viewableFieldsMap = item.getViewableFieldMap(currentUser); // pick up the non-file fields from the list above and put them here for a list view final List<Field> noFileViewableFieldNamesList = new ArrayList<Field>(); // Separate list view for files List<Field> fileViewableFieldNamesList = new ArrayList<Field>(); List<Field> simpleAtachmentViewableFieldNamesList = new ArrayList<Field>(); for (Field field : viewableFieldsMap.values()) { if (!field.getName().isFile()) { // is not file and not hidden (since we got it from getViewbleFieldList) noFileViewableFieldNamesList.add(field); } else { // if file and not simple attachment, keep for later simpleAtachmentViewableFieldNamesList if (field.getName().getText().equals(Field.FIELD_TYPE_SIMPLE_ATTACHEMENT)) { simpleAtachmentViewableFieldNamesList.add(field); } else { fileViewableFieldNamesList.add(field); } } } Metadata metadata = getCalipso().getCachedMetadataForSpace(item.getSpace()); final SimpleDateFormat dateFormat = metadata.getDateFormat(Metadata.DATE_FORMAT_LONG); List<FieldGroup> fieldGroupsList = metadata.getFieldGroups(); @SuppressWarnings("unchecked") ListView fieldGroups = new ListView("fieldGroups", fieldGroupsList) { @Override protected void populateItem(ListItem listItem) { // get group FieldGroup fieldGroup = (FieldGroup) listItem.getModelObject(); listItem.add(new Label("fieldGroupLabel", fieldGroup.getName())); List<Field> groupFields = fieldGroup.getFields(); List<Field> viewbleFieldGroups = new LinkedList<Field>(); // get group fields if (CollectionUtils.isNotEmpty(groupFields)) { for (Field field : groupFields) { // is viewalble? if (noFileViewableFieldNamesList.contains(field)) { viewbleFieldGroups.add(field); } } } ListView listView = new ListView("fields", viewbleFieldGroups) { @Override @SuppressWarnings("deprecation") protected void populateItem(ListItem listItem) { addFieldValueDisplay(item, sam, dateFormat, listItem); } }; if (viewbleFieldGroups.isEmpty()) { listItem.setVisible(false); } listView.setReuseItems(true); listItem.add(listView.setRenderBodyOnly(true)); } }; add(fieldGroups); // Iterates custom fields than are not type file // add(new ListView("CustomFieldsListView", noFileViewableFieldNamesList) { // protected void populateItem(ListItem listItem) { // addFieldValueDisplay(item, sam, dateFormat, listItem); // } // // // }); if (fileViewableFieldNamesList.size() > 0) { // add custom field type file label add(new Label("fileFieldLabel", localize("files"))); //add values for custom fields type file // check for if doesn't exist custom field type file // TODO: user should upload a file for every customField type file // get Attachments ArrayList<Attachment> itemAttachments = item.getAttachments() != null ? new ArrayList<Attachment>(item.getAttachments()) : new ArrayList(); //logger.info("Files to render: "+itemAttachments.size()); ListView fileCustomFieldsListView = new ListView("fileCustomFieldsListView", itemAttachments) { @Override protected void populateItem(ListItem listItem) { Attachment tmpAttachment = (Attachment) listItem.getModelObject(); listItem.add(new AttachmentDownLoadableLinkPanel("fileLink", tmpAttachment)); } }; add(fileCustomFieldsListView); } else { // add empty label add(new EmptyPanel("fileCustomFieldsListView").setVisible(false)); // add custom field type file label add(new Label("fileFieldLabel", localize("files"))); } // TODO: Dont think this actually checks for user roles rights within the State scope, // plus the *readable* fields are needed instead to feed the historyEntry ("history" ListView) bellow //final List<Field> editable = item.getSpace().getMetadata().getEditableFields(); final List<Field> readable = item.getSpace().getMetadata() .getReadableFields(currentUser.getSpaceRoles(item.getSpace()), item.getStatus()); add(new ListView("labels", readable) { @Override protected void populateItem(ListItem listItem) { Field field = (Field) listItem.getModelObject(); listItem.add(new Label("label", field.getLabel())); } }); currentUser.setRoleSpaceStdFieldList(getCalipso().findSpaceFieldsForUser(currentUser)); Map<StdField.Field, StdFieldMask> fieldMaskMap = currentUser.getStdFieldsForSpace(currentSpace); //Get user fields List<RoleSpaceStdField> stdFields = currentUser.getStdFields(); //Standard fields ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //List of standard Fields List<RoleSpaceStdField> standardFields = StdFieldsUtils.filterFieldsBySpace(stdFields, fieldMaskMap, currentSpace); //Render Standard field add(new ListView("stdFields", standardFields) { @Override protected void populateItem(ListItem listItem) { RoleSpaceStdField stdField = (RoleSpaceStdField) listItem.getModelObject(); boolean invisible = stdField.getStdField().getField().getFieldType().getType() .equals(StdFieldType.Type.ASSET) || stdField.getStdField().getField().getFieldType().getType() .equals(StdFieldType.Type.ASSETTYPE) || stdField.getStdField().getField().equals(StdField.Field.ACTUAL_EFFORT); listItem.add(new Label("label", localize("field." + stdField.getStdField().getField().getName())) .setVisible(!invisible)); IModel value = new Model(""); if (stdField.getStdField().getField().getFieldType().getType() .equals(StdFieldType.Type.STATISTIC)) { Method method = null; ReflectionUtils.buildFromProperty("get", stdField.getStdField().getField().getName()); try { method = item.getClass().getMethod(ReflectionUtils.buildFromProperty("get", stdField.getStdField().getField().getName())); value = new Model(ItemUtils.formatEffort(method.invoke(item), localize("item_list.days"), localize("item_list.hours"), localize("item_list.minutes"))); } catch (NoSuchMethodException noSuchMethodException) { logger.error(noSuchMethodException); } catch (InvocationTargetException invocationTargetException) { logger.error(invocationTargetException); } catch (IllegalAccessException illegalAccessException) { logger.error(illegalAccessException); } } else if (stdField.getStdField().getField().getFieldType().getType() .equals(StdFieldType.Type.INFO)) { if (stdField.getStdField().getField().equals(StdField.Field.DUE_TO)) { value = new Model(new StringBuffer().append(DateUtils.format(item.getStateDueTo())) .append(" / ").append(DateUtils.format(item.getDueTo())).toString()); if (item.getStatus() != State.CLOSED) { if (item.getDueTo() != null && item.getDueTo().before(Calendar.getInstance().getTime())) { listItem.add(new SimpleAttributeModifier("class", "dueToDate-alarm")); } //if else if (item.getDueTo() != null && item.getPlannedEffort() != null && item.getDueTo().after(Calendar.getInstance().getTime())) { DateTime dueToDateTime = new DateTime(item.getDueTo()); DateTime nowDateTime = new DateTime(Calendar.getInstance().getTime()); long restTimeToDueTo = DateTime.diff(nowDateTime, dueToDateTime).inSeconds() / 60; if (restTimeToDueTo < item.getPlannedEffort().longValue()) { listItem.add(new SimpleAttributeModifier("class", "dueToDate-warning")); } //if } } } //if else if (stdField.getStdField().getField().equals(StdField.Field.PLANNED_EFFORT)) { if (item.getPlannedEffort() != null) { value = new Model( new Effort(item.getPlannedEffort()).formatEffort(localize("item_list.days"), localize("item_list.hours"), localize("item_list.minutes"))); } } } listItem.add(new Label("value", value).setVisible(!invisible)); } }); //Assets ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //Space is integrated with asset or space is not but was perhaps in the past integrated and at least one asset was bind with this item boolean userCanViewAssets = fieldMaskMap.get(StdField.Field.ASSET) != null && !fieldMaskMap.get(StdField.Field.ASSET).getMask().equals(StdFieldMask.Mask.HIDDEN); boolean spaceIsUIntegratedWithAsset = item.getSpace().isAssetEnabled(); boolean userCanUpdateAssets = fieldMaskMap.get(StdField.Field.ASSET) != null && fieldMaskMap.get(StdField.Field.ASSET).getMask().equals(StdFieldMask.Mask.UPDATE); boolean userCanAdministrateAssetsForSpace = currentUser != null && currentUser.getId() != 0 && (currentUser.isGlobalAdmin() || currentUser.isSpaceAdmin(currentSpace)); boolean userCanSeeComments = currentUser.hasRegularRoleForSpace(currentSpace) || (currentSpace.getItemVisibility().equals(Space.ITEMS_VISIBLE_TO_LOGGEDIN_REPORTERS) && currentUser.isGuestForSpace(currentSpace)); if (userCanSeeComments) { // show history? userCanSeeComments = !(tmpl != null && tmpl.getHideHistory().booleanValue()); } WebMarkupContainer assetsContainer = new WebMarkupContainer("assetsContainer"); add(assetsContainer.setRenderBodyOnly(true)); ItemAssetsPanel itemAssetsPanel = new ItemAssetsPanel("itemAssetsViewPanel", item); WebMarkupContainer editAssetContainer = new WebMarkupContainer("editAssetContainer"); add(editContainer.setRenderBodyOnly(true)); editAssetContainer.add(new Link("editAsset") { @Override public void onClick() { //breadCrumb must be activated in the active panel, that is ItemViewPanel ((BreadCrumbPanel) getBreadCrumbModel().getActive()).activate(new IBreadCrumbPanelFactory() { @Override public BreadCrumbPanel create(String componentId, IBreadCrumbModel breadCrumbModel) { return new ItemAssetFormPanel(componentId, breadCrumbModel, item.getId()); } }); } }); editAssetContainer.setVisible(userCanUpdateAssets); assetsContainer.add(editAssetContainer); if (hideLinks) { editAssetContainer.setVisible(false); } // --- Link to Asset administration for assets SpaceAssetAdminLink spaceAssetAdminLink = new SpaceAssetAdminLink("asset", getBreadCrumbModel()) { @Override public void onLinkActivate() { //do nothing } }; assetsContainer.add(spaceAssetAdminLink); spaceAssetAdminLink.setVisible(userCanAdministrateAssetsForSpace); if (hideLinks) { spaceAssetAdminLink.setVisible(false); } //Case 1: //Current space is integrated with assets and user can view these assets //Case 2: //Current space is NOT integrated with assets BUT was integrated with assets in the past and user can view these assets //============ //Pseudo code: //============ // if (Case 1 OR Case 2) then // showAssets(); // fi // else // doNotShowAssets(); // esle boolean itemInvolvesAssets = itemAssetsPanel.getItemAssets() != null && itemAssetsPanel.getItemAssets().size() > 0; if ((spaceIsUIntegratedWithAsset && userCanViewAssets) || (!spaceIsUIntegratedWithAsset && itemInvolvesAssets && userCanViewAssets)) { itemAssetsPanel.renderItemAssets(); assetsContainer.add(itemAssetsPanel); } //if else { assetsContainer.setVisible(false); } //else WebMarkupContainer historyContainer = new WebMarkupContainer("historyContainer"); historyContainer.add(new WebMarkupContainer("historyComment").setVisible(userCanSeeComments)); if (item.getHistory() != null && userCanSeeComments) { List<History> history = new ArrayList(item.getHistory()); historyContainer.add(new ListView("history", history) { @Override protected void populateItem(ListItem listItem) { final History h = (History) listItem.getModelObject(); //First history entry is empty => Add item detail to first history item for view harmonization. if (listItem.getIndex() == 0) { h.setComment(item.getDetail()); h.setHtmlComment(item.getHtmlDetail()); } HistoryEntry historyEntry = new HistoryEntry("historyEntry", getBreadCrumbModel(), h, readable); if (listItem.getIndex() % 2 == 0) { historyEntry.add(sam); } listItem.add(historyEntry); } }.setRenderBodyOnly(true)); } else { historyContainer.add(new WebMarkupContainer("history").add(new WebMarkupContainer("historyEntry"))); historyContainer.setVisible(false); } add(historyContainer); }
From source file:info.jtrac.wicket.CustomFieldsFormPanel.java
License:Apache License
/** * This method allows to add components (custom fields). * * @param model/* w ww .j a v a 2 s .c o m*/ * @param fields * @param isEditMode */ private void addComponents(final BoundCompoundPropertyModel model, List<Field> fields, final boolean isEditMode) { ListView listView = new ListView("fields", fields) { @Override protected void populateItem(ListItem listItem) { final Field field = (Field) listItem.getModelObject(); boolean isRequired = isEditMode ? false : !field.isOptional(); listItem.add(new Label("label", field.getLabel())); listItem.add(new Label("star", isRequired ? "*" : " ").setEscapeModelStrings(false)); if (field.isDropDownType()) { Fragment f = new Fragment("field", "dropDown", CustomFieldsFormPanel.this); final Map<String, String> options = field.getOptions(); List<String> keys; // bound value if (options != null) { keys = new ArrayList<String>(options.keySet()); } else { keys = new ArrayList<String>(); } DropDownChoice choice = new DropDownChoice("field", keys, new IChoiceRenderer() { @Override public Object getDisplayValue(Object o) { return options.get(o); }; @Override public String getIdValue(Object o, int i) { return o.toString(); }; }); choice.setNullValid(true); choice.setLabel(new Model(field.getLabel())); choice.setRequired(isRequired); WebMarkupContainer border = new WebMarkupContainer("border"); f.add(border); border.add(new ErrorHighlighter(choice)); border.add(model.bind(choice, field.getName().getText())); listItem.add(f); } else if (field.isDatePickerType()) { /* * ====================================== * Date picker * ====================================== */ YuiCalendar calendar = new YuiCalendar("field", new PropertyModel(model, field.getName().getText()), isRequired); listItem.add(calendar); calendar.setLabel(new Model(field.getLabel())); } else { /* * ====================================== * Text field * ====================================== */ Fragment f = new Fragment("field", "textField", CustomFieldsFormPanel.this); TextField textField = new TextField("field"); /* * Check if the field is used to display/edit * Double values. */ if (field.isDecimalNumberType()) { /* * The following code overwrites the default * DoubleConverter used by Wicket (getConverter(Class)). * The original implementation rounds after three * digits to the right of the decimal point. * * As there are requirements to show six digits to * the right of the decimal point the NumberFormat * is enhanced in the code below by the DecimalFormat * class. That has been used because the DecimalFormat * class supports a formatting pattern which allows * to use the digits to the right only if really * needed (currently limited to six digits to the * right of the decimal point). */ textField = new TextField("field", Double.class) { @Override public org.apache.wicket.util.convert.IConverter getConverter( @SuppressWarnings("rawtypes") Class type) { DoubleConverter converter = (DoubleConverter) DoubleConverter.INSTANCE; java.text.NumberFormat numberFormat = converter.getNumberFormat(getLocale()); java.text.DecimalFormat decimalFormat = (java.text.DecimalFormat) numberFormat; decimalFormat.applyPattern("###,##0.######"); converter.setNumberFormat(getLocale(), decimalFormat); return converter; }; }; } textField.add(new ErrorHighlighter()); textField.setRequired(isRequired); textField.setLabel(new Model(field.getLabel())); f.add(model.bind(textField, field.getName().getText())); listItem.add(f); } } }; listView.setReuseItems(true); add(listView); }
From source file:info.jtrac.wicket.ExcelImportRowPage.java
License:Apache License
public ExcelImportRowPage(final ExcelImportPage previous, final int index) { add(new FeedbackPanel("feedback")); add(new Link("cancel") { public void onClick() { setResponsePage(previous);// w w w .ja v a 2 s .c o m } }); final ExcelFile excelFile = previous.getExcelFile(); final List<Cell> rowCells = excelFile.getRowCellsCloned(index); Form form = new Form("form") { @Override public void onSubmit() { excelFile.setRowCells(index, rowCells); setResponsePage(previous); } }; add(form); final SimpleAttributeModifier CLASS_SELECTED = new SimpleAttributeModifier("class", "selected"); ListView listView = new ListView("cells", rowCells) { protected void populateItem(ListItem item) { Column column = excelFile.getColumns().get(item.getIndex()); item.add(new Label("heading", column.getLabel())); final Cell cell = (Cell) item.getModelObject(); TextArea textArea = new TextArea("value"); textArea.setModel(new IModel() { public Object getObject() { return cell.getValue(); } public void setObject(Object o) { cell.setValue(o); } public void detach() { } }); textArea.setLabel(new Model(column.getLabel())); textArea.add(new ErrorHighlighter()); Object value = cell.getValue(); if (value != null) { if (value instanceof Date) { textArea.setType(Date.class); } else if (value instanceof Double) { textArea.setType(Double.class); } } item.add(textArea); if (column.getColumnHeading() != null) { item.add(CLASS_SELECTED); textArea.setEnabled(false); } } }; listView.setReuseItems(true); form.add(listView); }
From source file:it.av.eatt.web.page.RistoranteAddNewPage.java
License:Apache License
/** * Constructor that is invoked when page is invoked without a session. * //from w w w . j av a2 s .com * @throws JackWicketException */ public RistoranteAddNewPage() throws JackWicketException { ristorante = new Ristorante(); ristorante.addDescriptions(getDescriptionI18n()); form = new Form<Ristorante>("ristoranteForm", new CompoundPropertyModel<Ristorante>(ristorante)); add(getFeedbackPanel()); AjaxFormComponentUpdatingBehavior updatingBehavior = new AjaxFormComponentUpdatingBehavior("onchange") { private static final long serialVersionUID = 1L; @Override protected void onUpdate(AjaxRequestTarget arg0) { try { String ristoName = form.get(Ristorante.NAME).getDefaultModelObjectAsString(); Country ristoCountry = ((DropDownChoice<Country>) form.get(Ristorante.COUNTRY)) .getModelObject(); List<DataRistorante> ristosFound = new ArrayList<DataRistorante>( dataRistoranteService.getBy(ristoName, cityName, ristoCountry)); if (!(ristosFound.isEmpty())) { DataRistorante dataRistorante = ristosFound.get(0); form.get(Ristorante.ADDRESS).setDefaultModelObject(dataRistorante.getAddress()); form.get(Ristorante.FAX_NUMBER).setDefaultModelObject(dataRistorante.getFaxNumber()); form.get(Ristorante.PHONE_NUMBER).setDefaultModelObject(dataRistorante.getPhoneNumber()); form.get(Ristorante.POSTALCODE).setDefaultModelObject(dataRistorante.getPostalCode()); form.get(Ristorante.PROVINCE).setDefaultModelObject(dataRistorante.getProvince()); form.get(Ristorante.WWW).setDefaultModelObject(dataRistorante.getWww()); info(new StringResourceModel("info.autocompletedRistoSucces", form, null).getString()); arg0.addComponent(getFeedbackPanel()); arg0.addComponent(form); } } catch (Exception e) { error(new StringResourceModel("genericErrorMessage", form, null).getString()); new JackWicketRunTimeException(e); arg0.addComponent(getFeedbackPanel()); } } }; form.setOutputMarkupId(true); final RistoranteAutocompleteBox ristoName = new RistoranteAutocompleteBox(Ristorante.NAME, AutocompleteUtils.getAutoCompleteSettings()); ristoName.setRequired(true); ristoName.add(updatingBehavior); form.add(ristoName); form.add(new RequiredTextField<String>(Ristorante.ADDRESS)); CityAutocompleteBox city = new CityAutocompleteBox("city-autocomplete", AutocompleteUtils.getAutoCompleteSettings(), new Model<String>(cityName) { @Override public String getObject() { return cityName; } @Override public void setObject(String object) { cityName = (String) object; } }); // With this component the city model is updated correctly after every change city.add(new AjaxFormComponentUpdatingBehavior("onchange") { @Override protected void onUpdate(AjaxRequestTarget target) { // TODO Auto-generated method stub } }); city.add(new CityValidator()); form.add(city); form.add(new RequiredTextField<String>(Ristorante.PROVINCE)); form.add(new RequiredTextField<String>(Ristorante.POSTALCODE)); DropDownChoice<Country> country = new DropDownChoice<Country>(Ristorante.COUNTRY, countryService.getAll(), new CountryChoiceRenderer()); country.add(new OnChangeAjaxBehavior() { @Override protected void onUpdate(AjaxRequestTarget target) { } }); country.setRequired(true); form.add(country); form.add(new TextField<String>(Ristorante.PHONE_NUMBER)); form.add(new TextField<String>(Ristorante.FAX_NUMBER)); form.add(new TextField<String>(Ristorante.MOBILE_PHONE_NUMBER)); form.add(new TextField<String>(Ristorante.WWW)); form.add(new CheckBox("types.ristorante")); form.add(new CheckBox("types.pizzeria")); form.add(new CheckBox("types.bar")); ListView<RistoranteDescriptionI18n> descriptions = new ListView<RistoranteDescriptionI18n>("descriptions") { @Override protected void populateItem(ListItem<RistoranteDescriptionI18n> item) { item.add(new Label(RistoranteDescriptionI18n.LANGUAGE, getString(item.getModelObject().getLanguage().getCountry()))); item.add(new TextArea<String>(RistoranteDescriptionI18n.DESCRIPTION, new PropertyModel<String>(item.getModelObject(), RistoranteDescriptionI18n.DESCRIPTION))); } }; descriptions.setReuseItems(true); form.add(descriptions); buttonClearForm = new AjaxFallbackLink<Ristorante>("buttonClearForm", new Model<Ristorante>(ristorante)) { @Override public void onClick(AjaxRequestTarget target) { form.setModelObject(new Ristorante()); target.addComponent(form); } }; form.add(buttonClearForm); form.add(new SubmitButton("submitRestaurant", form)); submitRestaurantRight = new SubmitButton("submitRestaurantRight", form); submitRestaurantRight.setOutputMarkupId(true); add(submitRestaurantRight); // OnChangeAjaxBehavior onChangeAjaxBehavior = new OnChangeAjaxBehavior() { // @Override // protected void onUpdate(AjaxRequestTarget target) { // // label.setModelObject(getValue(city.getModelObjectAsString())); // // target.addComponent(label); // } // }; // city.add(onChangeAjaxBehavior); add(form); }
From source file:jp.gihyo.wicket.page.ajax.AjaxTimeline.java
License:Apache License
private void constructPage() { final TweetForm form = new TweetForm("tweetForm"); add(form);//from w w w.ja v a 2 s . c o m feedback = new FeedbackPanel("feedback"); feedback.setOutputMarkupId(true); add(feedback); IModel<List<Status>> statusModel = new LoadableDetachableModel<List<Status>>() { @Override protected List<Status> load() { try { Twitter twitter = AppSession.get().getTwitterSession(); return twitter.getFriendsTimeline(new Paging(currentPageNumber, ITEMS_PER_PAGE)); } catch (TwitterException ex) { AjaxTimeline.this.error(getString("canNotRetrieveFriendTimeline")); return Collections.emptyList(); } } }; ListView<Status> timeline = new ListView<Status>("statusView", statusModel) { @Override protected void populateItem(final ListItem<Status> item) { final Status status = item.getModelObject(); String userUrl = "http://twitter.com/" + status.getUser().getScreenName(); ExternalLink imageLink = new ExternalLink("imageLink", userUrl); //ImageR|?[lg?A<img>^Osrc??X`?X WebMarkupContainer userImage = new WebMarkupContainer("userImage"); userImage.add(new SimpleAttributeModifier("src", status.getUser().getProfileImageURL().toString())); imageLink.add(userImage); item.add(imageLink); ExternalLink screenNameLink = new ExternalLink("screenName", userUrl, status.getUser().getScreenName()); item.add(screenNameLink); Label content = new Label("tweetContent", status.getText()); item.add(content); ExternalLink tweetLink = new ExternalLink("tweetLink", userUrl + "/status/" + status.getId(), null); item.add(tweetLink); Label time = new Label("tweetTime", new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(status.getCreatedAt())); tweetLink.add(time); Label clientName = new Label("clientName", status.getSource()); item.add(clientName.setEscapeModelStrings(false)); /* * YXe?[^XCo^\xNX?B * ?\bh?A??[JNX`?B * ??[JNX?ANXOstatus?ANZX?B */ class FavorateLabel extends Label { private static final long serialVersionUID = -2194580825236126312L; private Status targetStatus; private boolean needRefresh; public FavorateLabel(String id) { super(id); this.targetStatus = status; setDefaultModel(new AbstractReadOnlyModel<String>() { @Override public String getObject() { try { if (needRefresh) { targetStatus = getCurrentStatus(status.getId()); needRefresh = false; } return targetStatus == null ? "" : targetStatus.isFavorited() ? "unfav" : "fav"; } catch (TwitterException ex) { LOGGER.error("Can not fetch current status for status id = " + status.getId(), ex); return "error"; } } }); } public void setNeedRefresh(boolean needRefresh) { this.needRefresh = needRefresh; } } //CNx final FavorateLabel favName = new FavorateLabel("favName"); favName.setOutputMarkupId(true); /* * AjaxCN?B * Xe?[^XCo^o^?Ao^???s?B * o^???AAjaxg?Ay?[WS?ACo^Xe?[^X * Nx??B */ AjaxLink<Void> favLink = new AjaxLink<Void>("favLink") { @Override public void onClick(AjaxRequestTarget target) { try { Status currentStatus = getCurrentStatus(status.getId()); Twitter twitterSession = AppSession.get().getTwitterSession(); if (currentStatus.isFavorited()) { twitterSession.destroyFavorite(currentStatus.getId()); info(getString("favorateRemoved")); } else { twitterSession.createFavorite(currentStatus.getId()); info(getString("favorateRegistered")); } favName.setNeedRefresh(true); target.addComponent(feedback); //o^?bZ?[W\?AtB?[hobNpl?X?V?B target.addComponent(favName); } catch (TwitterException ex) { String message = getString("catNotCreateFavorite") + ": " + ex.getStatusCode(); error(message); LOGGER.error(message, ex); } } }; item.add(favLink); favLink.add(favName); //AJAX LINK item.add(new AjaxLink<Void>("replyLink") { @Override public void onClick(AjaxRequestTarget target) { String targetScreenName = status.getUser().getScreenName(); form.insertText(target, "@" + targetScreenName + " "); } }); //Q?l?AreplyLinkJavaScriptp // item.add(new Link<Void>("replyLink") { // @Override // public void onClick() { // } // // @Override // protected CharSequence getOnClickScript(CharSequence url) { // return "getElementById('" + form.getTextAreaId() + "').value = '@" + status.getUser().getScreenName() + " ';" + // "getElementById('" + form.getTextAreaId() + "').focus(); return false;"; // } // }); } }; //ListView\e?s????BreuseItemsv?peB??A //y?[W\?Ay?[WTu~bg?AXgeIuWFNg\??B //twitterey?[We?X??AXg????AXge? //Xe?[^Xu?A??dv?B timeline.setReuseItems(true); add(timeline); /* * y?[WO?EirQ?[^ */ add(new PagingLink("paging", AjaxTimeline.class, new AbstractReadOnlyModel<Integer>() { @Override public Integer getObject() { return getCurrentPage(); } })); }
From source file:jp.gihyo.wicket.page.paging.PagingTimeline.java
License:Apache License
private void constructPage() { final TweetForm form = new TweetForm("tweetForm"); add(form);// w ww . j ava2 s . c om feedback = new FeedbackPanel("feedback"); feedback.setOutputMarkupId(true); add(feedback); /* * ^CCpIModel?B * ??[hf?[^NGXg?EX|X?ETCNLbV?A * LoadableDetachableModelNXgp?B */ IModel<List<Status>> statusModel = new LoadableDetachableModel<List<Status>>() { @Override protected List<Status> load() { try { Twitter twitter = AppSession.get().getTwitterSession(); return twitter.getFriendsTimeline(new Paging(currentPageNumber, ITEMS_PER_PAGE)); } catch (TwitterException ex) { PagingTimeline.this.error(getString("canNotRetrieveFriendTimeline")); return Collections.emptyList(); } } }; /* * ^CCXg */ ListView<Status> timeline = new ListView<Status>("statusView", statusModel) { @Override protected void populateItem(final ListItem<Status> item) { final Status status = item.getModelObject(); String userUrl = "http://twitter.com/" + status.getUser().getScreenName(); ExternalLink imageLink = new ExternalLink("imageLink", userUrl); //ImageR|?[lg?A<img>^Osrc??X`?X WebMarkupContainer userImage = new WebMarkupContainer("userImage"); userImage.add(new SimpleAttributeModifier("src", status.getUser().getProfileImageURL().toString())); imageLink.add(userImage); item.add(imageLink); ExternalLink screenNameLink = new ExternalLink("screenName", userUrl, status.getUser().getScreenName()); item.add(screenNameLink); Label content = new Label("tweetContent", status.getText()); item.add(content); ExternalLink tweetLink = new ExternalLink("tweetLink", userUrl + "/status/" + status.getId(), null); item.add(tweetLink); Label time = new Label("tweetTime", new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(status.getCreatedAt())); tweetLink.add(time); Label clientName = new Label("clientName", status.getSource()); item.add(clientName.setEscapeModelStrings(false)); /* * CNx?BIModel?f?A?fav/unfav * \?B */ final Label favName = new Label("favName", new AbstractReadOnlyModel<String>() { @Override public String getObject() { return status.isFavorited() ? "unfav" : "fav"; } }); /* * CN?BNbN?C?E??s?B */ Link<Void> favLink = new Link<Void>("favLink") { @Override public void onClick() { try { Twitter twitterSession = AppSession.get().getTwitterSession(); if (status.isFavorited()) { twitterSession.destroyFavorite(status.getId()); info(getString("favorateRemoved")); } else { twitterSession.createFavorite(status.getId()); info(getString("favorateRegistered")); } } catch (TwitterException ex) { String message = getString("catNotCreateFavorite") + ": " + ex.getStatusCode(); error(message); LOGGER.error(message, ex); } } }; item.add(favLink); favLink.add(favName); /* * vCpN?B * ?u@screenName?v?B */ item.add(new Link<Void>("replyLink") { @Override public void onClick() { String targetScreenName = status.getUser().getScreenName(); form.insertText("@" + targetScreenName + " "); } }); } }; //ListView\e?s????BreuseItemsv?peB??A //y?[W\?Ay?[WTu~bg?AXgeIuWFNg\??B //twitterey?[We?X??AXg????AXge? //Xe?[^Xu?A??dv?B timeline.setReuseItems(true); add(timeline); /* * y?[WO?EirQ?[^ */ add(new PagingLink("paging", PagingTimeline.class, new AbstractReadOnlyModel<Integer>() { @Override public Integer getObject() { return getCurrentPage(); } })); }