Search in sources :

Example 6 with BasicCollectionMetadata

use of org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata in project BroadleafCommerce by BroadleafCommerce.

the class FormBuilderServiceImpl method buildCollectionListGrid.

@Override
public ListGrid buildCollectionListGrid(String containingEntityId, DynamicResultSet drs, Property field, String sectionKey, List<SectionCrumb> sectionCrumbs) throws ServiceException {
    FieldMetadata fmd = field.getMetadata();
    // Get the class metadata for this particular field
    PersistencePackageRequest ppr = PersistencePackageRequest.fromMetadata(fmd, sectionCrumbs);
    if (field != null) {
        ppr.setSectionEntityField(field.getName());
    }
    ClassMetadata cmd = adminEntityService.getClassMetadata(ppr).getDynamicResultSet().getClassMetaData();
    List<Field> headerFields = new ArrayList<>();
    ListGrid.Type type = null;
    boolean editable = false;
    boolean sortable = false;
    boolean readOnly = false;
    boolean hideIdColumn = false;
    boolean canFilterAndSort = true;
    boolean modalSingleSelectable = false;
    boolean modalMultiSelectable = false;
    boolean selectize = false;
    boolean isMedia = false;
    boolean isLookup = false;
    String sortProperty = null;
    FieldWrapper wrapper = new FieldWrapper();
    ArrayList<FieldDTO> defaultWrapperFields = new ArrayList<>();
    String idProperty = "id";
    for (Property property : cmd.getProperties()) {
        if (property.getMetadata() instanceof BasicFieldMetadata && SupportedFieldType.ID == ((BasicFieldMetadata) property.getMetadata()).getFieldType() && // make sure it's a property for this entity - not an association
        !property.getName().contains(".")) {
            idProperty = property.getName();
            break;
        }
    }
    // kind of field this is.
    if (fmd instanceof BasicFieldMetadata) {
        readOnly = ((BasicFieldMetadata) fmd).getReadOnly();
        modalSingleSelectable = true;
        for (Property p : cmd.getProperties()) {
            if (p.getMetadata() instanceof BasicFieldMetadata) {
                BasicFieldMetadata md = (BasicFieldMetadata) p.getMetadata();
                if (SupportedFieldType.ID.equals(md.getFieldType())) {
                    idProperty = md.getName();
                }
                if (md.isProminent() != null && md.isProminent() && !ArrayUtils.contains(getGridHiddenVisibilities(), md.getVisibility())) {
                    Field hf = createHeaderField(p, md);
                    headerFields.add(hf);
                    defaultWrapperFields.add(constructFieldDTOFromFieldData(hf, md));
                }
                if (md.getIsFilter() != null && md.getIsFilter()) {
                    Field f = createHeaderField(p, md);
                    wrapper.getFields().add(constructFieldDTOFromFieldData(f, md));
                }
            }
        }
        type = ListGrid.Type.TO_ONE;
    } else if (fmd instanceof BasicCollectionMetadata) {
        BasicCollectionMetadata bcm = (BasicCollectionMetadata) fmd;
        readOnly = !bcm.isMutable();
        if (AddMethodType.LOOKUP.equals(bcm.getAddMethodType())) {
            isLookup = true;
        }
        if (AddMethodType.SELECTIZE_LOOKUP.equals(bcm.getAddMethodType())) {
            Property p = cmd.getPMap().get(bcm.getSelectizeVisibleField());
            if (p != null) {
                BasicFieldMetadata md = (BasicFieldMetadata) p.getMetadata();
                Field hf = createHeaderField(p, md);
                headerFields.add(hf);
                wrapper.getFields().add(constructFieldDTOFromFieldData(hf, md));
            }
        } else {
            for (Property p : cmd.getProperties()) {
                if (p.getMetadata() instanceof BasicFieldMetadata) {
                    BasicFieldMetadata md = (BasicFieldMetadata) p.getMetadata();
                    if (md.isProminent() != null && md.isProminent() && !ArrayUtils.contains(getGridHiddenVisibilities(), md.getVisibility())) {
                        Field hf = createHeaderField(p, md);
                        headerFields.add(hf);
                        defaultWrapperFields.add(constructFieldDTOFromFieldData(hf, md));
                    }
                    if (md.getIsFilter() != null && md.getIsFilter()) {
                        Field f = createHeaderField(p, md);
                        wrapper.getFields().add(constructFieldDTOFromFieldData(f, md));
                    }
                }
            }
        }
        type = ListGrid.Type.BASIC;
        if (AddMethodType.PERSIST.equals(bcm.getAddMethodType()) || AddMethodType.PERSIST_EMPTY.equals(bcm.getAddMethodType())) {
            editable = true;
        } else if (AddMethodType.SELECTIZE_LOOKUP.equals(bcm.getAddMethodType())) {
            selectize = true;
            modalSingleSelectable = true;
        } else {
            modalSingleSelectable = true;
        }
        sortable = StringUtils.isNotBlank(bcm.getSortProperty());
        if (sortable) {
            sortProperty = bcm.getSortProperty();
        }
    } else if (fmd instanceof AdornedTargetCollectionMetadata) {
        modalSingleSelectable = true;
        readOnly = !((AdornedTargetCollectionMetadata) fmd).isMutable();
        AdornedTargetCollectionMetadata atcmd = (AdornedTargetCollectionMetadata) fmd;
        if (AdornedTargetAddMethodType.LOOKUP.equals(atcmd.getAdornedTargetAddMethodType())) {
            isLookup = true;
        }
        if (AdornedTargetAddMethodType.SELECTIZE_LOOKUP.equals(atcmd.getAdornedTargetAddMethodType())) {
            selectize = true;
            Property p = cmd.getPMap().get(atcmd.getSelectizeVisibleField());
            if (p != null) {
                BasicFieldMetadata md = (BasicFieldMetadata) p.getMetadata();
                Field hf = createHeaderField(p, md);
                headerFields.add(hf);
                wrapper.getFields().add(constructFieldDTOFromFieldData(hf, md));
            }
        } else {
            for (String fieldName : atcmd.getGridVisibleFields()) {
                Property p = cmd.getPMap().get(fieldName);
                if (p != null) {
                    BasicFieldMetadata md = (BasicFieldMetadata) p.getMetadata();
                    Field hf = createHeaderField(p, md);
                    headerFields.add(hf);
                    wrapper.getFields().add(constructFieldDTOFromFieldData(hf, md));
                }
            }
        }
        type = ListGrid.Type.ADORNED;
        if (atcmd.getMaintainedAdornedTargetFields().length > 0) {
            editable = true;
        }
        AdornedTargetList adornedList = (AdornedTargetList) atcmd.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.ADORNEDTARGETLIST);
        sortable = StringUtils.isNotBlank(adornedList.getSortField());
        if (sortable) {
            sortProperty = adornedList.getSortField();
        }
    } else if (fmd instanceof MapMetadata) {
        readOnly = !((MapMetadata) fmd).isMutable();
        MapMetadata mmd = (MapMetadata) fmd;
        Property p2 = cmd.getPMap().get("key");
        BasicFieldMetadata keyMd = (BasicFieldMetadata) p2.getMetadata();
        keyMd.setFriendlyName(getMapKeyFriendlyName(p2));
        Field hf = createHeaderField(p2, keyMd);
        headerFields.add(hf);
        wrapper.getFields().add(constructFieldDTOFromFieldData(hf, keyMd));
        if (mmd.isSimpleValue()) {
            Property valueProperty = cmd.getPMap().get("value");
            BasicFieldMetadata valueMd = (BasicFieldMetadata) valueProperty.getMetadata();
            valueMd.setFriendlyName("Value");
            hf = createHeaderField(valueProperty, valueMd);
            headerFields.add(hf);
            wrapper.getFields().add(constructFieldDTOFromFieldData(hf, valueMd));
            idProperty = "key";
            hideIdColumn = true;
        } else {
            for (Property p : cmd.getProperties()) {
                if (p.getMetadata() instanceof BasicFieldMetadata) {
                    BasicFieldMetadata md = (BasicFieldMetadata) p.getMetadata();
                    String valueClassName = mmd.getValueClassName();
                    if (!StringUtils.isEmpty(mmd.getToOneTargetProperty())) {
                        Class<?> clazz;
                        try {
                            clazz = Class.forName(mmd.getValueClassName());
                        } catch (ClassNotFoundException e) {
                            throw ExceptionHelper.refineException(e);
                        }
                        java.lang.reflect.Field nestedField = FieldManager.getSingleField(clazz, mmd.getToOneTargetProperty());
                        ManyToOne manyToOne = nestedField.getAnnotation(ManyToOne.class);
                        if (manyToOne != null && !manyToOne.targetEntity().getName().equals(void.class.getName())) {
                            valueClassName = manyToOne.targetEntity().getName();
                        } else {
                            OneToOne oneToOne = nestedField.getAnnotation(OneToOne.class);
                            if (oneToOne != null && !oneToOne.targetEntity().getName().equals(void.class.getName())) {
                                valueClassName = oneToOne.targetEntity().getName();
                            }
                        }
                    }
                    if (md.getTargetClass().equals(valueClassName)) {
                        if (md.isProminent() != null && md.isProminent() && !ArrayUtils.contains(getGridHiddenVisibilities(), md.getVisibility())) {
                            hf = createHeaderField(p, md);
                            headerFields.add(hf);
                            defaultWrapperFields.add(constructFieldDTOFromFieldData(hf, md));
                            // Is this a media listgrid
                            if (hf.getFieldType().equals("ASSET_LOOKUP")) {
                                isMedia = true;
                            }
                        }
                        if (md.getIsFilter() != null && md.getIsFilter()) {
                            wrapper.getFields().add(constructFieldDTOFromFieldData(hf, md));
                        }
                    }
                }
            }
        }
        type = ListGrid.Type.MAP;
        editable = true;
        canFilterAndSort = false;
    }
    String ceilingType = "";
    if (fmd instanceof BasicFieldMetadata) {
        ceilingType = cmd.getCeilingType();
    } else if (fmd instanceof CollectionMetadata) {
        ceilingType = ((CollectionMetadata) fmd).getCollectionCeilingEntity();
    }
    if (CollectionUtils.isEmpty(headerFields)) {
        String message = "There are no listgrid header fields configured for the class " + ceilingType + " and property '" + StringUtil.sanitize(field.getName()) + "'.";
        if (selectize && (type == ListGrid.Type.ADORNED || type == ListGrid.Type.ADORNED_WITH_FORM)) {
            message += " Please configure 'selectizeVisibleField' in your @AdminPresentationAdornedTargetCollection configuration";
        } else if (type == ListGrid.Type.ADORNED || type == ListGrid.Type.ADORNED_WITH_FORM) {
            message += " Please configure 'gridVisibleFields' in your @AdminPresentationAdornedTargetCollection configuration";
        } else if (selectize && type == ListGrid.Type.BASIC) {
            message += " Please configure 'selectizeVisibleField' in your @AdminPresentationCollection configuration";
        } else {
            message += " Please mark some @AdminPresentation fields with 'prominent = true'";
        }
        LOG.error(message);
    }
    ListGrid listGrid = createListGrid(ceilingType, headerFields, type, drs, sectionKey, fmd.getOrder(), idProperty, sectionCrumbs, sortProperty);
    listGrid.setSubCollectionFieldName(field.getName());
    listGrid.setFriendlyName(field.getMetadata().getFriendlyName());
    if (StringUtils.isEmpty(listGrid.getFriendlyName())) {
        listGrid.setFriendlyName(field.getName());
    }
    listGrid.setContainingEntityId(containingEntityId);
    listGrid.setIsReadOnly(readOnly);
    listGrid.setHideIdColumn(hideIdColumn);
    listGrid.setCanFilterAndSort(canFilterAndSort);
    // Set up the filter builder params
    Date c = new Date();
    String friendlyName = field.getMetadata().getFriendlyName();
    String jsonFriendlyName = friendlyName.replaceAll(" ", "_");
    listGrid.setJsonFieldName(jsonFriendlyName + c.getTime() + "Json");
    listGrid.setFriendlyName(friendlyName);
    listGrid.setFieldBuilder("RULE_SIMPLE");
    if (CollectionUtils.isEmpty(wrapper.getFields())) {
        wrapper.setFields(defaultWrapperFields);
    }
    listGrid.setFieldWrapper(wrapper);
    String blankJsonString = "{\"data\":[]}";
    listGrid.setJson(blankJsonString);
    DataWrapper dw = convertJsonToDataWrapper(blankJsonString);
    if (dw != null) {
        listGrid.setDataWrapper(dw);
    }
    if (editable) {
        listGrid.getRowActions().add(DefaultListGridActions.UPDATE);
    }
    if (readOnly) {
        listGrid.getRowActions().add(DefaultListGridActions.VIEW);
    }
    if (sortable) {
        listGrid.setCanFilterAndSort(false);
        listGrid.setIsSortable(true);
    }
    if (modalSingleSelectable) {
        if (readOnly) {
            listGrid.addModalRowAction(DefaultListGridActions.SINGLE_SELECT.clone().withForListGridReadOnly(true));
        } else {
            listGrid.addModalRowAction(DefaultListGridActions.SINGLE_SELECT);
        }
    }
    listGrid.setSelectType(ListGrid.SelectType.SINGLE_SELECT);
    if (selectize) {
        listGrid.setSelectizeUrl(buildSelectizeUrl(listGrid));
        listGrid.setSelectType(ListGrid.SelectType.SELECTIZE);
    }
    if (modalMultiSelectable) {
        listGrid.addModalRowAction(DefaultListGridActions.MULTI_SELECT);
        listGrid.setSelectType(ListGrid.SelectType.MULTI_SELECT);
    }
    listGrid.getRowActions().add(DefaultListGridActions.REMOVE);
    if (fmd.getManualFetch()) {
        listGrid.setManualFetch(true);
        listGrid.getToolbarActions().add(DefaultListGridActions.MANUAL_FETCH);
    }
    if (isMedia) {
        listGrid.setListGridType(ListGrid.Type.ASSET_GRID);
    }
    extensionManager.getProxy().modifyListGrid(listGrid.getClassName(), listGrid);
    // If someone has replaced RowLevelSecurityService, check here to make sure the replacement implements the expected interface
    if (rowLevelSecurityService instanceof ExceptionAwareRowLevelSecurityProvider) {
        EntityFormModifierConfiguration entityFormModifierConfiguration = ((ExceptionAwareRowLevelSecurityProvider) rowLevelSecurityService).getUpdateDenialExceptions();
        for (EntityFormModifierData<EntityFormModifierDataPoint> data : entityFormModifierConfiguration.getData()) {
            for (EntityFormModifier modifier : entityFormModifierConfiguration.getModifier()) {
                if (modifier.isQualified(data.getModifierType())) {
                    modifier.modifyListGrid(new EntityFormModifierRequest().withListGrid(listGrid).withConfiguration(data).withCurrentUser(adminRemoteSecurityService.getPersistentAdminUser()).withRowLevelSecurityService(rowLevelSecurityService));
                }
            }
        }
    }
    return listGrid;
}
Also used : ClassMetadata(org.broadleafcommerce.openadmin.dto.ClassMetadata) FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) ArrayList(java.util.ArrayList) PersistencePackageRequest(org.broadleafcommerce.openadmin.server.domain.PersistencePackageRequest) EntityFormModifier(org.broadleafcommerce.openadmin.server.security.service.EntityFormModifier) ManyToOne(javax.persistence.ManyToOne) EntityFormModifierConfiguration(org.broadleafcommerce.openadmin.server.security.service.EntityFormModifierConfiguration) DataWrapper(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper) CodeField(org.broadleafcommerce.openadmin.web.form.entity.CodeField) RuleBuilderField(org.broadleafcommerce.openadmin.web.form.component.RuleBuilderField) Field(org.broadleafcommerce.openadmin.web.form.entity.Field) ComboField(org.broadleafcommerce.openadmin.web.form.entity.ComboField) MediaField(org.broadleafcommerce.openadmin.web.form.component.MediaField) OneToOne(javax.persistence.OneToOne) FieldWrapper(org.broadleafcommerce.openadmin.web.rulebuilder.dto.FieldWrapper) Property(org.broadleafcommerce.openadmin.dto.Property) AdornedTargetList(org.broadleafcommerce.openadmin.dto.AdornedTargetList) MapMetadata(org.broadleafcommerce.openadmin.dto.MapMetadata) FieldDTO(org.broadleafcommerce.openadmin.web.rulebuilder.dto.FieldDTO) BasicCollectionMetadata(org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata) AdornedTargetCollectionMetadata(org.broadleafcommerce.openadmin.dto.AdornedTargetCollectionMetadata) CollectionMetadata(org.broadleafcommerce.openadmin.dto.CollectionMetadata) EntityFormModifierDataPoint(org.broadleafcommerce.openadmin.server.security.service.EntityFormModifierDataPoint) ListGrid(org.broadleafcommerce.openadmin.web.form.component.ListGrid) Date(java.util.Date) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) EntityFormModifierRequest(org.broadleafcommerce.openadmin.server.security.service.EntityFormModifierRequest) ExceptionAwareRowLevelSecurityProvider(org.broadleafcommerce.openadmin.server.security.service.ExceptionAwareRowLevelSecurityProvider) BasicCollectionMetadata(org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata) AdornedTargetCollectionMetadata(org.broadleafcommerce.openadmin.dto.AdornedTargetCollectionMetadata)

Example 7 with BasicCollectionMetadata

use of org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata in project BroadleafCommerce by BroadleafCommerce.

the class FormBuilderServiceImpl method populateEntityForm.

@Override
public void populateEntityForm(ClassMetadata cmd, Entity entity, Map<String, DynamicResultSet> collectionRecords, EntityForm ef, List<SectionCrumb> sectionCrumbs) throws ServiceException {
    // Get the form with values for this entity
    populateEntityForm(cmd, entity, ef, sectionCrumbs);
    // Attach the sub-collection list grids and specialty UI support
    for (Property p : cmd.getProperties()) {
        if (p.getMetadata() instanceof BasicFieldMetadata) {
            continue;
        }
        if (!ArrayUtils.contains(p.getMetadata().getAvailableToTypes(), entity.getType()[0])) {
            continue;
        }
        if (collectionRecords != null) {
            DynamicResultSet subCollectionEntities = collectionRecords.get(p.getName());
            String containingEntityId = entity.getPMap().get(ef.getIdProperty()).getValue();
            ListGrid listGrid = buildCollectionListGrid(containingEntityId, subCollectionEntities, p, ef.getSectionKey(), sectionCrumbs);
            CollectionMetadata md = ((CollectionMetadata) p.getMetadata());
            if (md instanceof BasicCollectionMetadata) {
                PersistencePackageRequest ppr = PersistencePackageRequest.fromMetadata(md, sectionCrumbs);
                ClassMetadata collectionCmd = adminEntityService.getClassMetadata(ppr).getDynamicResultSet().getClassMetaData();
                if (collectionCmd.getPolymorphicEntities().getChildren().length != 0) {
                    List<ClassTree> entityTypes = collectionCmd.getPolymorphicEntities().getCollapsedClassTrees();
                    ListGridActionGroup actionGroup = new ListGridActionGroup().withName("Add");
                    for (ClassTree entityType : entityTypes) {
                        ListGridAction ADD = new ListGridAction(ListGridAction.ADD).withButtonClass(AddMethodType.PERSIST_EMPTY == ((BasicCollectionMetadata) md).getAddMethodType() ? "sub-list-grid-add-empty" : "sub-list-grid-add").withActionTargetEntity(entityType.getFullyQualifiedClassname()).withUrlPostfix("/add").withIconClass("fa fa-plus").withDisplayText(BLCMessageUtils.getMessage(entityType.getFriendlyName()));
                        actionGroup.getListGridActions().add(0, ADD);
                    }
                    listGrid.addToolbarActionGroup(actionGroup);
                } else {
                    listGrid.getToolbarActions().add(0, AddMethodType.PERSIST_EMPTY == ((BasicCollectionMetadata) md).getAddMethodType() ? DefaultListGridActions.ADD_EMPTY : DefaultListGridActions.ADD);
                }
            } else {
                listGrid.getToolbarActions().add(0, DefaultListGridActions.ADD);
            }
            if (subCollectionEntities.getUnselectedTabMetadata().get(md.getTab()) != null) {
                ef.addListGrid(cmd, listGrid, md.getTab(), md.getTabOrder(), md.getGroup(), true);
            } else {
                ef.addListGrid(cmd, listGrid, md.getTab(), md.getTabOrder(), md.getGroup(), false);
            }
        }
    }
    if (CollectionUtils.isEmpty(ef.getActions())) {
        ef.addAction(DefaultEntityFormActions.SAVE);
    }
    addDeleteActionIfAllowed(ef, cmd, entity);
    setReadOnlyState(ef, cmd, entity);
    // check for fields that should be hidden based on annotations
    setVisibilityBasedOnShowIfFieldEquals(cmd, entity, ef);
    extensionManager.getProxy().modifyDetailEntityForm(ef);
}
Also used : ClassMetadata(org.broadleafcommerce.openadmin.dto.ClassMetadata) ListGridAction(org.broadleafcommerce.openadmin.web.form.component.ListGridAction) BasicCollectionMetadata(org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata) AdornedTargetCollectionMetadata(org.broadleafcommerce.openadmin.dto.AdornedTargetCollectionMetadata) CollectionMetadata(org.broadleafcommerce.openadmin.dto.CollectionMetadata) ClassTree(org.broadleafcommerce.openadmin.dto.ClassTree) PersistencePackageRequest(org.broadleafcommerce.openadmin.server.domain.PersistencePackageRequest) ListGridActionGroup(org.broadleafcommerce.openadmin.web.form.component.ListGridActionGroup) ListGrid(org.broadleafcommerce.openadmin.web.form.component.ListGrid) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) BasicCollectionMetadata(org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata) Property(org.broadleafcommerce.openadmin.dto.Property) DynamicResultSet(org.broadleafcommerce.openadmin.dto.DynamicResultSet)

Example 8 with BasicCollectionMetadata

use of org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata in project BroadleafCommerce by BroadleafCommerce.

the class AdminProductController method showAddAdditionalSku.

protected String showAddAdditionalSku(HttpServletRequest request, HttpServletResponse response, Model model, String id, Map<String, String> pathVars) throws Exception {
    String collectionField = "additionalSkus";
    String mainClassName = getClassNameForSection(SECTION_KEY);
    List<SectionCrumb> sectionCrumbs = getSectionCrumbs(request, SECTION_KEY, id);
    ClassMetadata mainMetadata = service.getClassMetadata(getSectionPersistencePackageRequest(mainClassName, sectionCrumbs, pathVars)).getDynamicResultSet().getClassMetaData();
    Property collectionProperty = mainMetadata.getPMap().get(collectionField);
    FieldMetadata md = collectionProperty.getMetadata();
    PersistencePackageRequest ppr = PersistencePackageRequest.fromMetadata(md, sectionCrumbs).withCustomCriteria(new String[] { id });
    BasicCollectionMetadata fmd = (BasicCollectionMetadata) md;
    ClassMetadata cmd = service.getClassMetadata(ppr).getDynamicResultSet().getClassMetaData();
    // If the entity type isn't specified, we need to determine if there are various polymorphic types
    // for this entity.
    String entityType = null;
    if (request.getParameter("entityType") != null) {
        entityType = request.getParameter("entityType");
    }
    if (StringUtils.isBlank(entityType)) {
        if (cmd.getPolymorphicEntities().getChildren().length == 0) {
            entityType = cmd.getPolymorphicEntities().getFullyQualifiedClassname();
        } else {
            entityType = getDefaultEntityType();
        }
    } else {
        entityType = URLDecoder.decode(entityType, "UTF-8");
    }
    if (StringUtils.isBlank(entityType)) {
        List<ClassTree> entityTypes = getAddEntityTypes(cmd.getPolymorphicEntities());
        model.addAttribute("entityTypes", entityTypes);
        model.addAttribute("viewType", "modal/entityTypeSelection");
        model.addAttribute("entityFriendlyName", cmd.getPolymorphicEntities().getFriendlyName());
        String requestUri = request.getRequestURI();
        if (!request.getContextPath().equals("/") && requestUri.startsWith(request.getContextPath())) {
            requestUri = requestUri.substring(request.getContextPath().length() + 1, requestUri.length());
        }
        model.addAttribute("currentUri", requestUri);
        model.addAttribute("modalHeaderType", ModalHeaderType.ADD_ENTITY.getType());
        setModelAttributes(model, SECTION_KEY);
        return "modules/modalContainer";
    } else {
        ppr = ppr.withCeilingEntityClassname(entityType);
    }
    ClassMetadata collectionMetadata = service.getClassMetadata(ppr).getDynamicResultSet().getClassMetaData();
    EntityForm entityForm = formService.createEntityForm(collectionMetadata, sectionCrumbs);
    entityForm.setCeilingEntityClassname(ppr.getCeilingEntityClassname());
    entityForm.setEntityType(ppr.getCeilingEntityClassname());
    formService.removeNonApplicableFields(collectionMetadata, entityForm, ppr.getCeilingEntityClassname());
    entityForm.removeAction(DefaultEntityFormActions.DELETE);
    model.addAttribute("entityForm", entityForm);
    model.addAttribute("viewType", "modal/simpleAddEntity");
    model.addAttribute("currentUrl", request.getRequestURL().toString());
    model.addAttribute("modalHeaderType", ModalHeaderType.ADD_COLLECTION_ITEM.getType());
    model.addAttribute("collectionProperty", collectionProperty);
    setModelAttributes(model, SECTION_KEY);
    return "modules/modalContainer";
}
Also used : SectionCrumb(org.broadleafcommerce.openadmin.dto.SectionCrumb) ClassMetadata(org.broadleafcommerce.openadmin.dto.ClassMetadata) EntityForm(org.broadleafcommerce.openadmin.web.form.entity.EntityForm) FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) ClassTree(org.broadleafcommerce.openadmin.dto.ClassTree) PersistencePackageRequest(org.broadleafcommerce.openadmin.server.domain.PersistencePackageRequest) BasicCollectionMetadata(org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata) Property(org.broadleafcommerce.openadmin.dto.Property)

Example 9 with BasicCollectionMetadata

use of org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata in project BroadleafCommerce by BroadleafCommerce.

the class AdminBasicEntityController method buildAddCollectionItemModel.

/**
 * Builds out all of the model information needed for showing the add modal for collection items on both the initial GET
 * as well as after a POST with validation errors
 *
 * @param request
 * @param model
 * @param id
 * @param collectionField
 * @param sectionKey
 * @param collectionProperty
 * @param md
 * @param ppr
 * @return the appropriate view to display for the modal
 * @see {@link #addCollectionItem(HttpServletRequest, HttpServletResponse, Model, Map, String, String, EntityForm, BindingResult)}
 * @see {@link #showAddCollectionItem(HttpServletRequest, HttpServletResponse, Model, Map, String, String, MultiValueMap)}
 * @throws ServiceException
 */
protected String buildAddCollectionItemModel(HttpServletRequest request, HttpServletResponse response, Model model, String id, String collectionField, String sectionKey, Property collectionProperty, FieldMetadata md, PersistencePackageRequest ppr, EntityForm entityForm, Entity entity) throws ServiceException {
    // For requests to add a new collection item include the main class that the subsequent request comes from.
    // For instance, with basic collections we know the main associated class for a fetch through the ForeignKey
    // persistence item but map and adorned target lookups make a standard persistence request. This solution
    // fixes all cases.
    String mainClassName = getClassNameForSection(sectionKey);
    ppr.addCustomCriteria("owningClass=" + mainClassName);
    ppr.setAddOperationInspect(true);
    if (entityForm != null) {
        entityForm.clearFieldsMap();
    }
    List<SectionCrumb> sectionCrumbs = getSectionCrumbs(request, sectionKey, id);
    if (md instanceof BasicCollectionMetadata) {
        BasicCollectionMetadata fmd = (BasicCollectionMetadata) md;
        // and sometimes show a list grid to allow the user to associate an existing record.
        if (fmd.getAddMethodType().equals(AddMethodType.PERSIST)) {
            ClassMetadata collectionMetadata = service.getClassMetadata(ppr).getDynamicResultSet().getClassMetaData();
            if (entityForm == null) {
                entityForm = formService.createEntityForm(collectionMetadata, sectionCrumbs);
                entityForm.setCeilingEntityClassname(ppr.getCeilingEntityClassname());
                entityForm.setEntityType(ppr.getCeilingEntityClassname());
            } else {
                formService.populateEntityForm(collectionMetadata, entityForm, sectionCrumbs);
                formService.populateEntityFormFieldValues(collectionMetadata, entity, entityForm);
            }
            formService.removeNonApplicableFields(collectionMetadata, entityForm, ppr.getCeilingEntityClassname());
            entityForm.getTabs().iterator().next().getIsVisible();
            model.addAttribute("entityForm", entityForm);
            model.addAttribute("viewType", "modal/simpleAddEntity");
        } else {
            DynamicResultSet drs = service.getRecords(ppr).getDynamicResultSet();
            ListGrid listGrid = formService.buildCollectionListGrid(id, drs, collectionProperty, sectionKey, sectionCrumbs);
            listGrid.setPathOverride(request.getRequestURL().toString());
            if (AddMethodType.LOOKUP.equals(fmd.getAddMethodType()) || AddMethodType.SELECTIZE_LOOKUP.equals(fmd.getAddMethodType())) {
                listGrid.removeAllRowActions();
            }
            model.addAttribute("listGrid", listGrid);
            model.addAttribute("viewType", "modal/simpleSelectEntity");
        }
    } else if (md instanceof AdornedTargetCollectionMetadata) {
        AdornedTargetCollectionMetadata fmd = (AdornedTargetCollectionMetadata) md;
        // Even though this field represents an adorned target collection, the list we want to show in the modal
        // is the standard list grid for the target entity of this field
        ppr.setOperationTypesOverride(null);
        ppr.setType(PersistencePackageRequest.Type.STANDARD);
        ppr.setSectionEntityField(collectionField);
        ClassMetadata collectionMetadata = service.getClassMetadata(ppr).getDynamicResultSet().getClassMetaData();
        DynamicResultSet drs = service.getRecords(ppr).getDynamicResultSet();
        ListGrid listGrid = formService.buildCollectionListGrid(id, drs, collectionProperty, sectionKey, sectionCrumbs);
        listGrid.setSubCollectionFieldName(collectionField);
        listGrid.setPathOverride(request.getRequestURL().toString());
        listGrid.setFriendlyName(collectionMetadata.getPolymorphicEntities().getFriendlyName());
        if (entityForm == null) {
            entityForm = formService.buildAdornedListForm(fmd, ppr.getAdornedList(), id, false, sectionCrumbs, true);
            entityForm.setCeilingEntityClassname(ppr.getAdornedList().getAdornedTargetEntityClassname());
        } else {
            formService.buildAdornedListForm(fmd, ppr.getAdornedList(), id, false, entityForm, sectionCrumbs, true);
            formService.populateEntityFormFieldValues(collectionMetadata, entity, entityForm);
        }
        listGrid.setListGridType(ListGrid.Type.ADORNED);
        for (Entry<String, Field> entry : entityForm.getFields().entrySet()) {
            if (entry.getValue().getIsVisible()) {
                listGrid.setListGridType(ListGrid.Type.ADORNED_WITH_FORM);
                break;
            }
        }
        // This is part of an add, so we want to be able to filter/sort the listgrid
        listGrid.setIsSortable(false);
        listGrid.setCanFilterAndSort(true);
        listGrid.removeAllRowActions();
        model.addAttribute("listGrid", listGrid);
        model.addAttribute("entityForm", entityForm);
        model.addAttribute("viewType", "modal/adornedSelectEntity");
    } else if (md instanceof MapMetadata) {
        MapMetadata fmd = (MapMetadata) md;
        ClassMetadata collectionMetadata = service.getClassMetadata(ppr).getDynamicResultSet().getClassMetaData();
        if (entityForm == null) {
            entityForm = formService.buildMapForm(fmd, ppr.getMapStructure(), collectionMetadata, id);
        } else {
            formService.buildMapForm(fmd, ppr.getMapStructure(), collectionMetadata, id, entityForm);
            formService.populateEntityFormFieldValues(collectionMetadata, entity, entityForm);
        }
        model.addAttribute("entityForm", entityForm);
        model.addAttribute("viewType", "modal/mapAddEntity");
    }
    // Set the parent id on the entity form
    if (entityForm != null) {
        entityForm.setParentId(id);
    }
    model.addAttribute("currentUrl", request.getRequestURL().toString());
    model.addAttribute("modalHeaderType", ModalHeaderType.ADD_COLLECTION_ITEM.getType());
    model.addAttribute("collectionProperty", collectionProperty);
    setModelAttributes(model, sectionKey);
    return "modules/modalContainer";
}
Also used : SectionCrumb(org.broadleafcommerce.openadmin.dto.SectionCrumb) ClassMetadata(org.broadleafcommerce.openadmin.dto.ClassMetadata) Entry(java.util.Map.Entry) BasicCollectionMetadata(org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata) DynamicResultSet(org.broadleafcommerce.openadmin.dto.DynamicResultSet) ListGrid(org.broadleafcommerce.openadmin.web.form.component.ListGrid) MapMetadata(org.broadleafcommerce.openadmin.dto.MapMetadata) AdornedTargetCollectionMetadata(org.broadleafcommerce.openadmin.dto.AdornedTargetCollectionMetadata)

Example 10 with BasicCollectionMetadata

use of org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata in project BroadleafCommerce by BroadleafCommerce.

the class CollectionFieldMetadataProvider method buildCollectionMetadata.

protected void buildCollectionMetadata(Class<?> parentClass, Class<?> targetClass, Map<String, FieldMetadata> attributes, FieldInfo field, FieldMetadataOverride collectionMetadata, String prefix) {
    BasicCollectionMetadata serverMetadata = (BasicCollectionMetadata) attributes.get(field.getName());
    Class<?> resolvedClass = parentClass == null ? targetClass : parentClass;
    BasicCollectionMetadata metadata;
    if (serverMetadata != null) {
        metadata = serverMetadata;
    } else {
        metadata = new BasicCollectionMetadata();
    }
    metadata.setTargetClass(targetClass.getName());
    metadata.setFieldName(field.getName());
    if (collectionMetadata.getReadOnly() != null) {
        metadata.setMutable(!collectionMetadata.getReadOnly());
    }
    if (collectionMetadata.getAddMethodType() != null) {
        metadata.setAddMethodType(collectionMetadata.getAddMethodType());
    }
    if (collectionMetadata.getShowIfProperty() != null) {
        metadata.setShowIfProperty(collectionMetadata.getShowIfProperty());
    }
    if (collectionMetadata.getShowIfFieldEquals() != null) {
        metadata.setShowIfFieldEquals(collectionMetadata.getShowIfFieldEquals());
    }
    org.broadleafcommerce.openadmin.dto.OperationTypes dtoOperationTypes = new org.broadleafcommerce.openadmin.dto.OperationTypes(OperationType.BASIC, OperationType.BASIC, OperationType.BASIC, OperationType.BASIC, OperationType.BASIC);
    if (collectionMetadata.getAddType() != null) {
        dtoOperationTypes.setAddType(collectionMetadata.getAddType());
    }
    if (collectionMetadata.getRemoveType() != null) {
        dtoOperationTypes.setRemoveType(collectionMetadata.getRemoveType());
    }
    if (collectionMetadata.getFetchType() != null) {
        dtoOperationTypes.setFetchType(collectionMetadata.getFetchType());
    }
    if (collectionMetadata.getInspectType() != null) {
        dtoOperationTypes.setInspectType(collectionMetadata.getInspectType());
    }
    if (collectionMetadata.getUpdateType() != null) {
        dtoOperationTypes.setUpdateType(collectionMetadata.getUpdateType());
    }
    if (AddMethodType.LOOKUP == metadata.getAddMethodType() || AddMethodType.SELECTIZE_LOOKUP == metadata.getAddMethodType()) {
        dtoOperationTypes.setRemoveType(OperationType.NONDESTRUCTIVEREMOVE);
    }
    // don't allow additional non-persistent properties or additional foreign keys for an advanced collection datasource - they don't make sense in this context
    PersistencePerspective persistencePerspective;
    if (serverMetadata != null) {
        persistencePerspective = metadata.getPersistencePerspective();
        persistencePerspective.setOperationTypes(dtoOperationTypes);
    } else {
        persistencePerspective = new PersistencePerspective(dtoOperationTypes, new String[] {}, new ForeignKey[] {});
        metadata.setPersistencePerspective(persistencePerspective);
    }
    String foreignKeyName = null;
    if (serverMetadata != null) {
        foreignKeyName = ((ForeignKey) serverMetadata.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY)).getManyToField();
    }
    if (!StringUtils.isEmpty(collectionMetadata.getManyToField())) {
        foreignKeyName = collectionMetadata.getManyToField();
    }
    if (foreignKeyName == null && !StringUtils.isEmpty(field.getOneToManyMappedBy())) {
        foreignKeyName = field.getOneToManyMappedBy();
    }
    if (foreignKeyName == null && !StringUtils.isEmpty(field.getManyToManyMappedBy())) {
        foreignKeyName = field.getManyToManyMappedBy();
    }
    if (StringUtils.isEmpty(foreignKeyName)) {
        throw new IllegalArgumentException("Unable to infer a ManyToOne field name for the @AdminPresentationCollection annotated field(" + field.getName() + "). If not using the mappedBy property of @OneToMany or @ManyToMany, please make sure to explicitly define the manyToField property");
    }
    String sortProperty = null;
    if (serverMetadata != null) {
        sortProperty = ((ForeignKey) serverMetadata.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY)).getSortField();
    }
    if (!StringUtils.isEmpty(collectionMetadata.getSortProperty())) {
        sortProperty = collectionMetadata.getSortProperty();
    }
    Boolean isAscending = true;
    if (serverMetadata != null) {
        isAscending = ((ForeignKey) serverMetadata.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY)).getSortAscending();
    }
    if (collectionMetadata.isSortAscending() != null) {
        isAscending = collectionMetadata.isSortAscending();
    }
    if (serverMetadata != null) {
        ForeignKey foreignKey = (ForeignKey) metadata.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
        foreignKey.setManyToField(foreignKeyName);
        foreignKey.setForeignKeyClass(resolvedClass.getName());
        foreignKey.setMutable(metadata.isMutable());
        foreignKey.setOriginatingField(prefix + field.getName());
        foreignKey.setSortField(sortProperty);
        foreignKey.setSortAscending(isAscending);
    } else {
        ForeignKey foreignKey = new ForeignKey(foreignKeyName, resolvedClass.getName(), null, ForeignKeyRestrictionType.ID_EQ);
        foreignKey.setMutable(metadata.isMutable());
        foreignKey.setOriginatingField(prefix + field.getName());
        foreignKey.setSortField(sortProperty);
        foreignKey.setSortAscending(isAscending);
        persistencePerspective.addPersistencePerspectiveItem(PersistencePerspectiveItemType.FOREIGNKEY, foreignKey);
    }
    String ceiling = null;
    checkCeiling: {
        if (field.getGenericType() instanceof ParameterizedType) {
            try {
                ParameterizedType pt = (ParameterizedType) field.getGenericType();
                java.lang.reflect.Type collectionType = pt.getActualTypeArguments()[0];
                String ceilingEntityName = ((Class<?>) collectionType).getName();
                ceiling = entityConfiguration.lookupEntityClass(ceilingEntityName).getName();
                break checkCeiling;
            } catch (NoSuchBeanDefinitionException e) {
            // We weren't successful at looking at entity configuration to find the type of this collection.
            // We will continue and attempt to find it via the Hibernate annotations
            }
        }
        if (!StringUtils.isEmpty(field.getOneToManyTargetEntity()) && !void.class.getName().equals(field.getOneToManyTargetEntity())) {
            ceiling = field.getOneToManyTargetEntity();
            break checkCeiling;
        }
        if (!StringUtils.isEmpty(field.getManyToManyTargetEntity()) && !void.class.getName().equals(field.getManyToManyTargetEntity())) {
            ceiling = field.getManyToManyTargetEntity();
            break checkCeiling;
        }
    }
    if (!StringUtils.isEmpty(ceiling)) {
        metadata.setCollectionCeilingEntity(ceiling);
    }
    if (collectionMetadata.getExcluded() != null) {
        if (LOG.isDebugEnabled()) {
            if (collectionMetadata.getExcluded()) {
                LOG.debug("buildCollectionMetadata:Excluding " + field.getName() + " because it was explicitly declared in config");
            } else {
                LOG.debug("buildCollectionMetadata:Showing " + field.getName() + " because it was explicitly declared in config");
            }
        }
        metadata.setExcluded(collectionMetadata.getExcluded());
    }
    if (collectionMetadata.getLazyFetch() != null) {
        metadata.setLazyFetch(collectionMetadata.getLazyFetch());
    }
    if (collectionMetadata.getManualFetch() != null) {
        metadata.setManualFetch(collectionMetadata.getManualFetch());
    }
    if (collectionMetadata.getFriendlyName() != null) {
        metadata.setFriendlyName(collectionMetadata.getFriendlyName());
    }
    if (collectionMetadata.getAddFriendlyName() != null) {
        metadata.setAddFriendlyName(collectionMetadata.getAddFriendlyName());
    }
    if (collectionMetadata.getSecurityLevel() != null) {
        metadata.setSecurityLevel(collectionMetadata.getSecurityLevel());
    }
    if (collectionMetadata.getOrder() != null) {
        metadata.setOrder(collectionMetadata.getOrder());
    }
    if (collectionMetadata.getTab() != null) {
        metadata.setTab(collectionMetadata.getTab());
    }
    if (collectionMetadata.getTabOrder() != null) {
        metadata.setTabOrder(collectionMetadata.getTabOrder());
    }
    if (collectionMetadata.getGroup() != null) {
        metadata.setGroup(collectionMetadata.getGroup());
    }
    if (collectionMetadata.getSortProperty() != null) {
        metadata.setSortProperty(collectionMetadata.getSortProperty());
    }
    if (collectionMetadata.getCustomCriteria() != null) {
        metadata.setCustomCriteria(collectionMetadata.getCustomCriteria());
    }
    if (collectionMetadata.getUseServerSideInspectionCache() != null) {
        persistencePerspective.setUseServerSideInspectionCache(collectionMetadata.getUseServerSideInspectionCache());
    }
    if (collectionMetadata.getCurrencyCodeField() != null) {
        metadata.setCurrencyCodeField(collectionMetadata.getCurrencyCodeField());
    }
    if (collectionMetadata.getSelectizeVisibleField() != null) {
        metadata.setSelectizeVisibleField(collectionMetadata.getSelectizeVisibleField());
    }
    attributes.put(field.getName(), metadata);
}
Also used : ForeignKey(org.broadleafcommerce.openadmin.dto.ForeignKey) ParameterizedType(java.lang.reflect.ParameterizedType) PersistencePerspective(org.broadleafcommerce.openadmin.dto.PersistencePerspective) AdminPresentationOperationTypes(org.broadleafcommerce.common.presentation.AdminPresentationOperationTypes) BasicCollectionMetadata(org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException)

Aggregations

BasicCollectionMetadata (org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata)18 FieldMetadata (org.broadleafcommerce.openadmin.dto.FieldMetadata)14 PersistencePackageRequest (org.broadleafcommerce.openadmin.server.domain.PersistencePackageRequest)13 Property (org.broadleafcommerce.openadmin.dto.Property)12 BasicFieldMetadata (org.broadleafcommerce.openadmin.dto.BasicFieldMetadata)11 ClassMetadata (org.broadleafcommerce.openadmin.dto.ClassMetadata)10 AdornedTargetCollectionMetadata (org.broadleafcommerce.openadmin.dto.AdornedTargetCollectionMetadata)9 Entity (org.broadleafcommerce.openadmin.dto.Entity)8 MapMetadata (org.broadleafcommerce.openadmin.dto.MapMetadata)8 SectionCrumb (org.broadleafcommerce.openadmin.dto.SectionCrumb)8 HashMap (java.util.HashMap)6 ListGrid (org.broadleafcommerce.openadmin.web.form.component.ListGrid)5 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 PersistenceResponse (org.broadleafcommerce.openadmin.server.service.persistence.PersistenceResponse)4 NoSuchBeanDefinitionException (org.springframework.beans.factory.NoSuchBeanDefinitionException)4 Field (java.lang.reflect.Field)3 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 AdminMainEntity (org.broadleafcommerce.common.admin.domain.AdminMainEntity)3 AdminPresentationCollectionOverride (org.broadleafcommerce.common.presentation.override.AdminPresentationCollectionOverride)3