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

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

Introduction

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

Prototype

public AjaxFormComponentUpdatingBehavior(final String event) 

Source Link

Document

Construct.

Usage

From source file:eu.uqasar.web.pages.tree.panels.thresholds.ThresholdEditor.java

License:Apache License

/**
 * Returns a Color selector that changes background color according to the
 * selected option/*w w w  .  j ava  2s.  com*/
 * 
 * @param model
 * @param name
 * @return
 */
private DropDownChoice<QualityStatus> choiceColorMenu(final IModel<Type> model, final String name) {
    final DropDownChoice<QualityStatus> choice = new DropDownChoice<QualityStatus>(name,
            Arrays.asList(QualityStatus.values())) {

        /**
         * 
         */
        private static final long serialVersionUID = -3202203242057441930L;

        @Override
        protected void onConfigure() {
            super.onConfigure();
            this.setDefaultModel(new PropertyModel<QualityStatus>(model, name));
        }
    };

    choice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        /**
         * 
         */
        private static final long serialVersionUID = -6980046265508585744L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            target.add(indicatorThreshold);
        }
    });

    return choice;
}

From source file:eu.uqasar.web.pages.user.panels.UserProfilePanel.java

License:Apache License

private DateTextField newDateTextField(final String id, IModel<Date> model) {
    Language language = Language.fromSession();
    DateTextFieldConfig config = new DateTextFieldConfig().withFormat(language.getDatePattern())
            .withLanguage(language.getLocale().getLanguage()).allowKeyboardNavigation(true).autoClose(false)
            .highlightToday(true).showTodayButton(true).withEndDate(DateTime.now());

    DateTextField dateTextField = new DateTextField(id, model, config);
    dateTextField.add(new AttributeAppender("placeHolder", language.getLocalizedDatePattern()));
    dateTextField.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        private static final long serialVersionUID = -7155018344656574747L;

        @Override//from ww  w  . ja  v  a2  s.  com
        protected void onUpdate(AjaxRequestTarget target) {
            target.add(age);
        }
    });
    return dateTextField;
}

From source file:gr.abiss.calipso.wicket.asset.AssetCustomAttributeFormPanel.java

License:Open Source License

private void addType(final CompoundPropertyModel model, final boolean isMandatory) {
    // attributeTypeList is a an object that contains a list of
    // attributeTypes
    // and a Map of pairs (AttributeTypes,AttributeTypes)
    //final AttributeTypes attributeTypesList = new AttributeTypes();

    logger.debug("addType, isMandatory: " + isMandatory);
    type = new DropDownChoice<Integer>("formType", new ArrayList<Integer>(CustomAttribute.FORM_TYPES),
            new IChoiceRenderer<Integer>() {
                @Override//from   w w  w.  j ava2  s.  c o m
                public Object getDisplayValue(Integer o) {
                    return localize("asset.attributeType_" + o.toString());
                }

                @Override
                public String getIdValue(Integer object, int index) {
                    return index + "";
                }
            }) {
        private static final long serialVersionUID = 1L;

        /**
         * @see org.apache.wicket.Component#initModel()
         */
        @Override
        protected boolean wantOnSelectionChangedNotifications() {
            return true;
        }

        //         @Override
        //         protected void onSelectionChanged(Integer newSelection) {
        //            if (isMandatory) {
        //               AssetCustomAttributeFormPanel.this.remove(validPanel);
        //               if (newSelection.equals(AssetTypeCustomAttribute.FORM_TYPE_MULTISELECT)
        //                     || newSelection.equals(AssetTypeCustomAttribute.FORM_TYPE_SELECT)
        //                     || newSelection.equals(AssetTypeCustomAttribute.FORM_TYPE_OPTIONS_TREE)) {
        //                  optionsPanel = new CustomAttributeOptionsPanel("optionTranslationsPanel", (AssetTypeCustomAttribute) model.getObject(), getCalipso().getSupportedLanguages(), textAreaOptions);
        //                  AssetCustomAttributeFormPanel.this.add(validPanel);
        //               }
        //               else if (newSelection.equals(AssetTypeCustomAttribute.FORM_TYPE_TEXT)) {
        //                     validPanel = new ValidationPanel("validPanel", model, isMandatory);
        //                     AssetCustomAttributeFormPanel.this.add(validPanel);
        //                  }
        //                  else{
        //                  AssetCustomAttributeFormPanel.this.add(new EmptyPanel("validPanel"));
        //               }
        //            }
        //            setModelObject(newSelection);
        //         }

        //         /**
        //          * @see
        //          * org.apache.wicket.markup.html.form.AbstractSingleSelectChoice
        //          * #getDefaultChoice(java.lang.Object)
        //          */
        //         @Override
        //         protected CharSequence getDefaultChoice(Object selected) {
        //            // TODO Auto-generated method stub
        //            return super
        //                  .getDefaultChoice(AssetTypeCustomAttribute.FORM_TYPE_TEXT);
        //         }
    };
    type.setOutputMarkupId(true);
    type.add(new AjaxFormComponentUpdatingBehavior("onchange") {

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            logger.info("onUpdate");
            if (isMandatory) {
                // AssetCustomAttributeFormPanel.this.remove(validPanel);
                Integer selected = type.getModelObject();

                if (selected.equals(AssetTypeCustomAttribute.FORM_TYPE_MULTISELECT)
                        || selected.equals(AssetTypeCustomAttribute.FORM_TYPE_SELECT)
                        || selected.equals(AssetTypeCustomAttribute.FORM_TYPE_OPTIONS_TREE)) {
                    optionsPanel.setVisible(true);
                    validPanel.setVisible(false);
                } else if (selected.equals(AssetTypeCustomAttribute.FORM_TYPE_TEXT)) {
                    optionsPanel.setVisible(false);
                    validPanel.setVisible(true);
                } else {
                    optionsPanel.setVisible(false);
                    validPanel.setVisible(false);
                }
                target.add(optionsPanelContainer);
                target.add(validPanelContainer);
            }
        }
    });

    type.setNullValid(false);
    type.setEnabled(this.assetTypeCanBeModified);
    type.setOutputMarkupId(true);
    add(type);

    type.setModel(new PropertyModel(model.getObject(), "formType"));
    // form label for form type
    type.setLabel(new ResourceModel("asset.customAttributes.type"));

    add(new SimpleFormComponentLabel("formTypeLabel", type));
    if (isMandatory) {
        type.setRequired(true);
        type.add(new ErrorHighlighter());
    }
}

From source file:gr.abiss.calipso.wicket.asset.ItemAssetsPanel.java

License:Open Source License

private void renderAvailableAssets(final IModel availableAssetsModel) {
    //Container ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    final WebMarkupContainer assetsContainer = new WebMarkupContainer("assetsContainer");
    assetsContainer.setOutputMarkupId(true);

    add(assetsContainer);/*from  w  w  w.j a  va 2s. c  om*/

    //Asset filter(s) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    WebMarkupContainer assetFIlterContainer = new WebMarkupContainer("assetFIlterContainer");
    //assetFIlterContainer.setRenderBodyOnly(true);
    assetsContainer.add(assetFIlterContainer);

    //Asset Type Filter
    //DropDownChoice assetTypeFIlter = renderAssetTypeFilter(assetsContainer, availableAssetsModel, this.availableAssetTypesList);

    // assettype dropDown

    final DropDownChoice assetTypeChoice = new DropDownChoice("assetTypeChoice", new Model(),
            this.availableAssetTypesList, new IChoiceRenderer() {
                public Object getDisplayValue(Object o) {
                    return localize(((AssetType) o).getNameTranslationResourceKey());
                }

                public String getIdValue(Object o, int i) {
                    return String.valueOf(((AssetType) o).getId());
                }
            });
    assetTypeChoice.setOutputMarkupId(true);

    assetTypeChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {

        protected void onUpdate(AjaxRequestTarget target) {

            if (assetTypeChoice.getModelObject() != null) {
                AssetType assetType = (AssetType) assetTypeChoice.getModelObject();
                assetSearch.getAsset().setAssetType(getCalipso().loadAssetType(assetType.getId()));
            } //if
            else {
                assetSearch.getAsset().setAssetType(null);
            } //else

            try {
                // remove table with assets
                assetsContainer.remove(itemAssetsListContainer);
            } catch (Exception e) {

            }
            // create again new fragment with search queries (currentSpace, assetType)
            Fragment itemAssetsListContainerFragment = new Fragment("itemAssetsListPlaceHolder",
                    "itemAssetsListContainerFragment", assetsContainer);
            if (isEditMode) {
                itemAssetsListContainerFragment.add(renderAssetList(getAllAssetsForCurrentItem(), false));
            } else {
                itemAssetsListContainerFragment.add(renderAssetList(getRemainingAssets(), false));
            }
            assetsContainer.add(itemAssetsListContainerFragment);
            target.addComponent(assetsContainer);
        }
    });

    boolean hasAvailableAssets = CollectionUtils.isNotEmpty(this.availableAssetTypesList);

    List<Asset> spaceAssets = new ArrayList<Asset>(getCalipso().getVisibleAssetsForSpace(getCurrentSpace()));
    boolean spaceHasAssets = CollectionUtils.isNotEmpty(spaceAssets);

    assetTypeChoice.setNullValid(false);
    assetFIlterContainer.add(new WebMarkupContainer("assetTypeFIlterLabel").setVisible(hasAvailableAssets));
    assetFIlterContainer.add(assetTypeChoice.setVisible(hasAvailableAssets));

    //Asset Inventory Code
    WebMarkupContainer assetCodeContainer = renderAssetCodeFilter();
    assetCodeContainer.setVisible(hasAvailableAssets);
    assetFIlterContainer.add(assetCodeContainer);
    assetCodeContainer.setVisible(false);

    //Asset List ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    itemAssetsListPlaceHolder = new WebMarkupContainer("itemAssetsListPlaceHolder");
    assetsContainer.add(itemAssetsListPlaceHolder);
    ItemAssetsPanel.this.itemAssetsListContainer = itemAssetsListPlaceHolder;
    ItemAssetsPanel.this.itemAssetsListContainer.setOutputMarkupId(false);

    // Messages ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    if (!hasAvailableAssets) {
        assetsContainer
                .add(new Label("noAssetMessage", new Model(localize("asset.assetPanel.noAvailableAssets"))));
    } else {
        assetsContainer.add(new WebMarkupContainer("noAssetMessage").setVisible(false));
    }
}

From source file:gr.abiss.calipso.wicket.asset.ItemAssetsPanel.java

License:Open Source License

/**
 * //from  w  w  w  . j a  v  a  2 s  .  c  o  m
 * @param assetsModel
 * @param isViewMode
 * @return 
 */
private WebMarkupContainer renderAssetList(final IModel assetsModel, final boolean isViewMode) {

    //Assets list container ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    final WebMarkupContainer itemAssetsListContainer = new WebMarkupContainer("itemAssetsListContainer");

    //Assets list ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    final SimpleAttributeModifier sam = new SimpleAttributeModifier("class", "alt");

    if (!isViewMode) {
        Label hCheckbox = new Label("hCheckbox", localize("asset.assetPanel.choose"));
        itemAssetsListContainer.add(hCheckbox);
    } else {
        itemAssetsListContainer.add(new WebMarkupContainer("hCheckbox").setVisible(false));
    }

    ListView assetsListView = new ListView("assetsList", assetsModel) {
        protected void populateItem(final ListItem listItem) {
            if (listItem.getIndex() % 2 != 0) {
                listItem.add(sam);
            } //if

            final Asset asset = (Asset) listItem.getModelObject();

            WebMarkupContainer chooseContainer = new WebMarkupContainer("chooseContainer");
            listItem.add(chooseContainer);

            if (!isViewMode) {
                // TODO:
                final CheckBox chooseAssetCheckBox = new CheckBox("choose",
                        new Model(selectedAssets.contains(asset)));

                if (isEditMode) {
                    if (allItemAssetsList.contains(asset)) {
                        chooseAssetCheckBox.setDefaultModelObject(new String("1"));
                        selectedAssets.add(asset);
                    } //if
                } //if
                chooseContainer.add(chooseAssetCheckBox);
                chooseAssetCheckBox.setOutputMarkupId(true);

                chooseAssetCheckBox.add(new AjaxFormComponentUpdatingBehavior("onchange") {
                    @Override
                    protected void onUpdate(AjaxRequestTarget target) {
                        if (chooseAssetCheckBox.getModelObject() != null) {
                            Boolean isSelected = (Boolean) chooseAssetCheckBox.getModelObject();
                            if (isSelected.equals(true)) {
                                selectedAssets.add(asset);
                            } else {
                                selectedAssets.remove(asset);
                            }
                        }
                    }
                });
            } else {
                chooseContainer.add(new WebMarkupContainer("choose").setVisible(false));
                chooseContainer.setVisible(false);
            } //else

            // --- Asset Type ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            Label assetType = new Label("assetType",
                    localize(asset.getAssetType().getNameTranslationResourceKey()));
            listItem.add(assetType);

            final WebMarkupContainer customAttributesContainer = new WebMarkupContainer(
                    "customAttributesContainer");
            customAttributesContainer.setOutputMarkupId(true);
            listItem.add(customAttributesContainer);

            final WebMarkupContainer customAttributesPanelContainer = new WebMarkupContainer(
                    "customAttributesPanel");
            customAttributesPanelContainer.setOutputMarkupId(true);
            customAttributesContainer.add(customAttributesPanelContainer);

            ExpandCustomAttributesLink customAttributesLink = new ExpandCustomAttributesLink(
                    "showCustomAttributesLink", asset);
            customAttributesLink.setComponentWhenCollapsed(customAttributesPanelContainer);
            customAttributesLink.setTargetComponent(customAttributesContainer);
            customAttributesLink.setImageWhenCollapsed(new CollapsedPanel("imagePanel"));
            customAttributesLink.setImageWhenExpanded(new ExpandedPanel("imagePanel"));

            CollapsedPanel imagePanel = new CollapsedPanel("imagePanel");
            customAttributesLink.add(imagePanel);

            listItem.add(customAttributesLink);

            // --- Inventory Code ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            listItem.add(new Label("inventoryCode", asset.getInventoryCode()));
            //format and display dates
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

            // --- Support Start Date ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            if (asset.getSupportStartDate() != null) {
                listItem.add(new Label("supportStartDate", dateFormat.format(asset.getSupportStartDate()))
                        .add(new SimpleAttributeModifier("class", "date")));
            } else {
                listItem.add(new Label("supportStartDate", ""));
            }

            // --- Support End Date ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            if (asset.getSupportEndDate() != null) {
                listItem.add(new Label("supportEndDate", dateFormat.format(asset.getSupportEndDate()))
                        .add(AssetsUtils.getSupportEndDateStyle(asset.getSupportEndDate())));
            } else {
                listItem.add(new Label("supportEndDate", ""));
            }

        }
    };
    itemAssetsListContainer.add(assetsListView);
    itemAssetsListContainer.setOutputMarkupId(true);

    return itemAssetsListContainer;
}

From source file:gr.abiss.calipso.wicket.asset.ItemFormAssetSearchPanel.java

License:Open Source License

public ItemFormAssetSearchPanel(String id, AssetSearch as) {
    super(id);/*from   w  w w.j  a va2  s.co m*/
    this.setOutputMarkupId(true);
    this.setVisible(true);
    final AssetSearch assetSearch = as;
    this.setDefaultModel(new CompoundPropertyModel(assetSearch));

    final WebMarkupContainer assetSearchForm = new WebMarkupContainer("assetAjaxSearchForm");
    assetSearchForm.setOutputMarkupId(true);
    add(assetSearchForm);
    assetSearchForm.add(new AjaxLink("close") {

        @Override
        public void onClick(AjaxRequestTarget target) {
            closePanel(target);
        }

    });
    // inventory code
    final TextField inventoryCode = new TextField("asset.inventoryCode");
    inventoryCode.setLabel(new ResourceModel("asset.inventoryCode"));
    inventoryCode.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        protected void onUpdate(AjaxRequestTarget target) {
            // Reset the inventoryCode model dropdown when the vendor changes
            assetSearch.getAsset().setInventoryCode(inventoryCode.getDefaultModelObjectAsString());
        }
    });
    assetSearchForm.add(inventoryCode);
    assetSearchForm.add(new SimpleFormComponentLabel("assetInventoryCodeLabel", inventoryCode));

    AssetSearchDataProvider assetSearchDataProvider = new AssetSearchDataProvider(assetSearch);
    // if AssetSearch only addresses one AssetType, do not allow other choices
    List<AssetType> assetTypes = null;
    if (assetSearch.getAsset().getAssetType() != null) {
        assetTypes = new ArrayList<AssetType>(1);
        assetTypes.add(assetSearch.getAsset().getAssetType());
    } else {
        assetTypes = getCalipso().findAllAssetTypes();
    }
    @SuppressWarnings("serial")
    final DropDownChoice assetTypeChoice = new DropDownChoice("asset.assetType", assetTypes,
            new IChoiceRenderer() {
                public Object getDisplayValue(Object o) {
                    return localize(((AssetType) o).getNameTranslationResourceKey());
                }

                public String getIdValue(Object o, int i) {
                    return localize(((AssetType) o).getName());
                }
            });
    if (assetTypes.size() == 1) {
        logger.debug("Only allow one Asset TypeChoice");
        assetTypeChoice.setNullValid(false).setRequired(true);
    } else {
        logger.debug("Only any AssetType Choice");
    }

    // List view headers 
    List<String> columnHeaders = assetSearch.getColumnHeaders();

    ListView headings = new ListView("headings", columnHeaders) {

        private static final long serialVersionUID = 1L;

        protected void populateItem(ListItem listItem) {
            final String header = (String) listItem.getModelObject();
            AjaxLink headingLink = new AjaxLink("heading") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    assetSearch.doSort(header);
                    target.addComponent(ItemFormAssetSearchPanel.this);
                }
            };

            listItem.add(headingLink);
            String label = localize("asset.assetsList." + header);
            headingLink.add(new Label("heading", label));
            if (header.equals(assetSearch.getSortFieldName())) {
                String order = assetSearch.isSortDescending() ? "order-down" : "order-up";
                listItem.add(new SimpleAttributeModifier("class", order));
            }
        }
    };
    assetSearchForm.add(headings);

    //Header message 
    Label hAction = new Label("hAction");
    hAction.setDefaultModel(new Model(localize("edit")));
    assetSearchForm.add(hAction);

    // the DataView with the results of the search
    final AssetsDataView assetDataView = new AssetsDataView("assetDataView", assetSearchDataProvider,
            getBreadCrumbModel(), getCalipso().getRecordsPerPage()) {

        // when click the add button
        @Override
        public void onAddAssetClick(Asset asset, AjaxRequestTarget target) {
            // re-render
            onAssetSelect(asset, target);
        }
    };
    assetSearchForm.add(assetDataView);

    AjaxPagingNavigator panelNavigator = new AjaxPagingNavigator("navigator", assetDataView) {
        @Override
        protected void onAjaxEvent(AjaxRequestTarget target) {
            target.addComponent(ItemFormAssetSearchPanel.this);
        }
    };
    assetSearchForm.add(panelNavigator);

    // back to our asset type choice....
    assetSearchForm.add(assetTypeChoice);
    assetTypeChoice.setLabel(new ResourceModel("asset.assetType"));
    // Add Ajax Behaviour...
    assetTypeChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        protected void onUpdate(AjaxRequestTarget target) {
            // Reset the phone model dropdown when the vendor changes
            assetDataView.setCurrentPage(0);
            assetSearch.getAsset().setAssetType((AssetType) assetTypeChoice.getModelObject());
        }
    });
    assetSearchForm.add(new SimpleFormComponentLabel("assetTypeLabel", assetTypeChoice));
    AjaxLink submitLink = new AjaxLink("submit") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            //assetSearchForm.replace(getConfiguredAssetListPanel(assetSearch));
            target.addComponent(ItemFormAssetSearchPanel.this);
        }
    };
    assetSearchForm.add(submitLink);
}

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/* w ww .  j  av a 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.ItemSearchForm.java

License:Open Source License

private void addComponents() {
    final Form form = new Form("form");
    Space space = getCurrentSpace();//from   w w  w .j  a va 2  s.c  o  m
    final boolean hideSummary = space != null && !space.isItemSummaryEnabled();
    add(form);
    form.add(new FeedbackPanel("feedback"));
    form.setModel(new CompoundPropertyModel(itemSearch));
    List<Integer> sizes = Arrays.asList(new Integer[] { 5, 10, 15, 25, 50, 100 });
    DropDownChoice pageSizeChoice = new DropDownChoice("pageSize", sizes, new IChoiceRenderer() {
        public Object getDisplayValue(Object o) {
            return ((Integer) o) == -1 ? localize("item_search_form.noLimit") : o.toString();
        }

        public String getIdValue(Object o, int i) {
            return o.toString();
        }
    });
    form.add(pageSizeChoice);
    //form label for page size
    pageSizeChoice.setLabel(new ResourceModel("item_search_form.resultsPerPage"));
    form.add(new SimpleFormComponentLabel("pageSizeLabel", pageSizeChoice));

    //showHistoryLabel
    CheckBox showHistoryCheckBox = new CheckBox("showHistory");
    form.add(showHistoryCheckBox);
    //form label for showHistoryLabel
    showHistoryCheckBox.setLabel(new ResourceModel("item_search_form.showHistory"));
    form.add(new SimpleFormComponentLabel("showHistoryLabel", showHistoryCheckBox));

    form.add(new Button("search") {
        @Override
        public void onSubmit() {
            String refId = itemSearch.getRefId();
            if (refId != null) {
                // user can save typing by entering the refId number without the space prefixCode
                // and the space sequence number.
                // User also search by item number without to select a space. 
                try {
                    long id = Long.parseLong(refId);
                    //Load item in order to get first and last part from item  
                    Item item = getCalipso().loadItem(id);

                    //If item doesn't exists
                    if (item == null) {
                        //Set a dummy value, in order to raise "item not found" instead of "Invalid reference id" 
                        refId = "0-0-0";
                    } //if
                    else {
                        refId = item.getUniqueRefId();
                    } //else
                } catch (Exception e) {
                    // oops that didn't work, continue
                }

                try {
                    new ItemRefId(refId);
                } catch (InvalidRefIdException e) {
                    form.error(localize("item_search_form.error.refId.invalid"));
                    return;
                }
                final Item item = getCalipso().loadItem(Item.getItemIdFromUniqueRefId(refId));
                if (item == null) {
                    form.error(localize("item_search_form.error.refId.notFound"));
                    return;
                }
                setCurrentItemSearch(itemSearch);
                activate(new IBreadCrumbPanelFactory() {
                    public BreadCrumbPanel create(String componentId, IBreadCrumbModel breadCrumbModel) {
                        return new ItemViewPanel(componentId, breadCrumbModel, item.getUniqueRefId());
                    }

                });
                return;
            }
            String searchText = itemSearch.getSearchText();
            if (searchText != null) {
                if (!getCalipso().validateTextSearchQuery(searchText)) {
                    form.error(localize("item_search_form.error.summary.invalid"));
                    return;
                }
            }
            setCurrentItemSearch(itemSearch);
            activate(new IBreadCrumbPanelFactory() {
                public BreadCrumbPanel create(String componentId, IBreadCrumbModel breadCrumbModel) {
                    return new ItemListPanel(componentId, breadCrumbModel);
                }
            });
        }
    });
    form.add(new Link("expandAll") {
        public void onClick() {
            expandAll = true;
        }

        @Override
        public boolean isVisible() {
            return !expandAll;
        }
    });

    form.add(new ListView("columns", itemSearch.getColumnHeadings()) {
        protected void populateItem(final ListItem listItem) {
            final ColumnHeading ch = (ColumnHeading) listItem.getModelObject();
            boolean enabled = true;
            if (ch.getName() != null && ch.getName().equals(SUMMARY) && hideSummary) {
                enabled = false;
            }

            String label = ch.isField() ? localize(ch.getLabel()) : localize("item_list." + ch.getNameText());

            CheckBox visibleCheckBox = new CheckBox("visible", new PropertyModel(ch, "visible"));
            visibleCheckBox.setEnabled(enabled);

            listItem.add(visibleCheckBox);

            //form Label
            visibleCheckBox.setLabel(new ResourceModel("", label));
            listItem.add(new SimpleFormComponentLabel("columnLabel", visibleCheckBox));

            List<Expression> validExpressions = ch.getValidFilterExpressions();
            DropDownChoice expressionChoice = new IndicatingDropDownChoice("expression", validExpressions,
                    new IChoiceRenderer() {
                        public Object getDisplayValue(Object o) {
                            String key = ((Expression) o).getKey();
                            return localize("item_filter." + key);
                        }

                        public String getIdValue(Object o, int i) {
                            return ((Expression) o).getKey();
                        }
                    });
            expressionChoice.setEnabled(enabled);
            if (ch.getName() == ID) {
                ch.getFilterCriteria().setExpression(Expression.EQ);
            }
            Component fragParent = null;

            if (expandAll) {
                ch.getFilterCriteria().setExpression(validExpressions.get(0));
                fragParent = ch.getFilterUiFragment(form, getPrincipal(), getCurrentSpace(), getCalipso());
            } else {
                fragParent = getFilterUiFragment(form, ch);
            }

            fragParent.setOutputMarkupId(true);
            listItem.add(fragParent);
            expressionChoice.setModel(new PropertyModel(ch.getFilterCriteria(), "expression"));
            expressionChoice.setNullValid(true);
            listItem.add(expressionChoice);
            expressionChoice.add(new AjaxFormComponentUpdatingBehavior("onChange") {
                protected void onUpdate(AjaxRequestTarget target) {
                    if (!ch.getFilterCriteria().requiresUiFragmentUpdate()) {
                        return;
                    }

                    Component fragment = getFilterUiFragment(form, ch);
                    fragment.setOutputMarkupId(true);
                    listItem.replace(fragment);
                    target.addComponent(fragment);
                    target.appendJavaScript(
                            "document.getElementById('" + fragment.getMarkupId() + "').focus()");
                }
            });
        }
    });
}

From source file:gr.abiss.calipso.wicket.SearchOnAnotherSpacePanel.java

License:Open Source License

private void addComponents() {
    final List<Space> userSpaces = new ArrayList<Space>(getPrincipal().getSpaces());

    if (getCurrentSpace() != null) {
        //Use, for all space search
        Space emptySpace = new Space();
        emptySpace.setId(0);/*from www. jav  a2 s .  c  o  m*/
        emptySpace.setName(localize("item_search_form.allSpaces"));
        emptySpace.setPrefixCode("");

        userSpaces.add(0, emptySpace);
        userSpaces.remove(getCurrentSpace());
    }

    // -- Spaces Drop Down List ------------------------------------------- 
    final DropDownChoice allSpaces = new DropDownChoice("allSpaces", new Model(), userSpaces,
            new IChoiceRenderer() {
                public String getIdValue(Object object, int index) {
                    return String.valueOf(((Space) object).getId());
                }

                public Object getDisplayValue(Object object) {
                    return localize(((Space) object).getNameTranslationResourceKey());
                }
            });
    allSpaces.setNullValid(false);
    allSpaces.setOutputMarkupId(true);

    allSpaces.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        protected void onUpdate(AjaxRequestTarget target) {
            //Do nothing. Needed for get its value via ajax.
        }//onUpdate
    });

    add(allSpaces);

    // -- Search Button -------------------------------------------
    final AjaxLink go = new AjaxLink("go") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            target.addComponent(allSpaces);
            if (allSpaces.getValue() != null && !allSpaces.getValue().equals("")
                    && !allSpaces.getValue().equals("-1")) {
                if (allSpaces.getValue().equals("0")) {//All Spaces
                    ((CalipsoSession) getSession()).setCurrentSpace(null);
                    setResponsePage(ItemSearchFormPage.class);
                } //if
                else {
                    Space selectedSpace = getCalipso().loadSpace(Long.parseLong(allSpaces.getValue()));
                    for (Space space : userSpaces) {
                        if (space.equals(selectedSpace)) {
                            setCurrentSpace(space);
                            setResponsePage(ItemSearchFormPage.class);
                        } //if
                    } //for
                } //else
            }
        }
    };
    go.setOutputMarkupId(true);
    add(go);
}

From source file:gr.abiss.calipso.wicket.SearchUserPanel.java

License:Open Source License

private WebMarkupContainer renderSearchCriteria() {
    final WebMarkupContainer searchFormContainer = new WebMarkupContainer("searchFormContainer");
    searchFormContainer.setOutputMarkupId(true);

    List<String> searchOnOptions = Arrays
            .asList(new String[] { "loginName", "name", "lastname", "email", "address", "phone" });

    searchOnChoice = new DropDownChoice("searchOn", new PropertyModel(SearchUserPanel.this, "searchOn"),
            searchOnOptions, new IChoiceRenderer() {
                public Object getDisplayValue(Object o) {
                    String s = (String) o;
                    return localize("user_list." + s);
                }/*from  w  ww  .  j a  va 2s .c  o  m*/

                public String getIdValue(Object o, int i) {
                    return o.toString();
                }
            });
    searchOnChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            searchOn = searchOnChoice.getDefaultModelObjectAsString();
            target.addComponent(searchFormContainer);

        }
    });
    searchFormContainer.add(searchOnChoice);

    searchTextField = new TextField("searchText", new PropertyModel(SearchUserPanel.this, "searchText"));
    searchTextField.setOutputMarkupId(true);
    searchTextField.add(new AjaxFormComponentUpdatingBehavior("onchange") {

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            searchText = searchTextField.getDefaultModelObjectAsString();
            target.addComponent(searchFormContainer);

        }
    });
    searchFormContainer.add(searchTextField);

    searchFormContainer.add(new Behavior() {
        public void renderHead(IHeaderResponse response) {
            response.renderOnLoadJavaScript(
                    "document.getElementById('" + searchTextField.getMarkupId() + "').focus()");
        }
    });

    AjaxLink submit = new AjaxLink("submit") {
        @Override
        public void onClick(AjaxRequestTarget target) {

            if (usersDataViewContainer != null) {
                searchFormContainer.remove(usersDataViewContainer);
            }
            searchFormContainer.add(renderUserDataView());
            target.addComponent(searchFormContainer);
        }
    };
    searchFormContainer.add(submit);
    searchFormContainer.add(renderUsersDataViewContainer(false));
    return searchFormContainer;
}