Search in sources :

Example 1 with Formatter

use of io.jmix.ui.component.formatter.Formatter in project jmix by jmix-framework.

the class AbstractDataGridLoader method loadAggregation.

@SuppressWarnings("unchecked")
protected void loadAggregation(DataGrid.Column column, Element columnElement) {
    Element aggregationElement = columnElement.element("aggregation");
    if (aggregationElement != null) {
        AggregationInfo aggregation = new AggregationInfo();
        aggregation.setPropertyPath(column.getPropertyPath());
        loadAggregationType(aggregation, aggregationElement);
        loadValueDescription(column, aggregationElement);
        Formatter formatter = loadFormatter(aggregationElement);
        aggregation.setFormatter(formatter == null ? (Formatter<Object>) column.getDescriptionProvider() : formatter);
        column.setAggregation(aggregation);
        loadStrategyClass(aggregation, aggregationElement);
        if (aggregation.getType() == null && aggregation.getStrategy() == null) {
            throw new GuiDevelopmentException("Incorrect aggregation - type or strategyClass is required", context);
        }
    }
}
Also used : Formatter(io.jmix.ui.component.formatter.Formatter) Element(org.dom4j.Element) GuiDevelopmentException(io.jmix.ui.GuiDevelopmentException)

Example 2 with Formatter

use of io.jmix.ui.component.formatter.Formatter in project jmix by jmix-framework.

the class ComponentLoaderHelper method loadFormatter.

@Nullable
public static Formatter<?> loadFormatter(Element element, ClassManager classManager, ComponentLoader.Context context) {
    Element formatterElement = element.element("formatter");
    if (formatterElement != null) {
        String className = formatterElement.attributeValue("class");
        if (StringUtils.isEmpty(className)) {
            throw new GuiDevelopmentException("Formatter's attribute 'class' is not specified", context);
        }
        Class<?> aClass = classManager.findClass(className);
        if (aClass == null) {
            throw new GuiDevelopmentException(String.format("Class %s is not found", className), context);
        }
        try {
            Constructor<?> constructor = aClass.getConstructor(Element.class);
            try {
                return (Formatter<?>) constructor.newInstance(formatterElement);
            } catch (Throwable e) {
                throw new GuiDevelopmentException(String.format("Unable to instantiate class %s: %s", className, e), context);
            }
        } catch (NoSuchMethodException e) {
            try {
                return (Formatter<?>) aClass.getDeclaredConstructor().newInstance();
            } catch (Exception e1) {
                throw new GuiDevelopmentException(String.format("Unable to instantiate class %s: %s", className, e1), context);
            }
        }
    } else {
        return null;
    }
}
Also used : Formatter(io.jmix.ui.component.formatter.Formatter) Element(org.dom4j.Element) GuiDevelopmentException(io.jmix.ui.GuiDevelopmentException) GuiDevelopmentException(io.jmix.ui.GuiDevelopmentException) Nullable(javax.annotation.Nullable)

Example 3 with Formatter

use of io.jmix.ui.component.formatter.Formatter in project jmix by jmix-framework.

the class ListEmbeddingStrategy method getColumnFormatter.

@SuppressWarnings("rawtypes")
protected Formatter getColumnFormatter(AttributeDefinition attribute) {
    if (attribute.getDataType() == AttributeType.ENUMERATION) {
        if (!attribute.isCollection()) {
            return value -> {
                if (value == null) {
                    return null;
                } else {
                    return msgBundleTools.getLocalizedEnumeration(attribute.getEnumerationMsgBundle(), (String) value);
                }
            };
        }
    } else if (!Strings.isNullOrEmpty(attribute.getConfiguration().getNumberFormatPattern())) {
        return value -> {
            if (value == null) {
                return null;
            } else {
                DecimalFormatSymbols symbols = new DecimalFormatSymbols(currentAuthentication.getLocale());
                DecimalFormat format = new DecimalFormat(attribute.getConfiguration().getNumberFormatPattern(), symbols);
                return format.format(value);
            }
        };
    }
    return null;
}
Also used : Strings(com.google.common.base.Strings) CurrentAuthentication(io.jmix.core.security.CurrentAuthentication) Formatter(io.jmix.ui.component.formatter.Formatter) AttributeDefinition(io.jmix.dynattr.AttributeDefinition) AttributeType(io.jmix.dynattr.AttributeType) DecimalFormatSymbols(java.text.DecimalFormatSymbols) MsgBundleTools(io.jmix.dynattr.MsgBundleTools) DecimalFormat(java.text.DecimalFormat) Autowired(org.springframework.beans.factory.annotation.Autowired) DecimalFormatSymbols(java.text.DecimalFormatSymbols) DecimalFormat(java.text.DecimalFormat)

Example 4 with Formatter

use of io.jmix.ui.component.formatter.Formatter in project jmix by jmix-framework.

the class FieldGroupLoader method loadField.

protected FieldGroup.FieldConfig loadField(Element element, Datasource ds, String columnWidth) {
    String id = element.attributeValue("id");
    String property = element.attributeValue("property");
    if (Strings.isNullOrEmpty(id) && Strings.isNullOrEmpty(property)) {
        throw new GuiDevelopmentException(String.format("id/property is not defined for field of FieldGroup '%s'. " + "Set id or property attribute.", resultComponent.getId()), context);
    }
    if (Strings.isNullOrEmpty(property)) {
        property = id;
    } else if (Strings.isNullOrEmpty(id)) {
        id = property;
    }
    Datasource targetDs = ds;
    Datasource datasource = loadDatasource(element);
    if (datasource != null) {
        targetDs = datasource;
    }
    CollectionDatasource optionsDs = null;
    String optDsName = element.attributeValue("optionsDatasource");
    if (StringUtils.isNotBlank(optDsName)) {
        LegacyFrame frame = (LegacyFrame) getComponentContext().getFrame().getFrameOwner();
        DsContext dsContext = frame.getDsContext();
        optionsDs = findDatasourceRecursively(dsContext, optDsName);
        if (optionsDs == null) {
            throw new GuiDevelopmentException(String.format("Options datasource %s not found for field %s", optDsName, id), context);
        }
    }
    boolean customField = false;
    String custom = element.attributeValue("custom");
    if (StringUtils.isNotEmpty(custom)) {
        customField = Boolean.parseBoolean(custom);
    }
    if (StringUtils.isNotEmpty(element.attributeValue("generator"))) {
        customField = true;
    }
    List<Element> elements = element.elements();
    List<Element> customElements = elements.stream().filter(e -> !("formatter".equals(e.getName()) || "validator".equals(e.getName()))).collect(Collectors.toList());
    if (!customElements.isEmpty()) {
        if (customElements.size() > 1) {
            throw new GuiDevelopmentException(String.format("FieldGroup field %s element cannot contains two or more custom field definitions", id), context);
        }
        if (customField) {
            throw new GuiDevelopmentException(String.format("FieldGroup field %s cannot use both custom/generator attribute and inline component definition", id), context);
        }
        customField = true;
    }
    if (!customField && targetDs == null) {
        throw new GuiDevelopmentException(String.format("Datasource is not defined for FieldGroup field '%s'. " + "Only custom fields can have no datasource.", property), context);
    }
    FieldGroup.FieldConfig field = resultComponent.createField(id);
    if (property != null) {
        field.setProperty(property);
    }
    if (datasource != null) {
        field.setDatasource(datasource);
    }
    if (optionsDs != null) {
        field.setOptionsDatasource(optionsDs);
    }
    String stylename = element.attributeValue("stylename");
    if (StringUtils.isNotEmpty(stylename)) {
        field.setStyleName(stylename);
    }
    MetaPropertyPath metaPropertyPath = null;
    if (targetDs != null && property != null) {
        MetaClass metaClass = targetDs.getMetaClass();
        metaPropertyPath = getMetadataTools().resolveMetaPropertyPathOrNull(targetDs.getMetaClass(), property);
        if (metaPropertyPath == null) {
            if (!customField) {
                throw new GuiDevelopmentException(String.format("Property '%s' is not found in entity '%s'", property, metaClass.getName()), context);
            }
        }
    }
    String propertyName = metaPropertyPath != null ? metaPropertyPath.getMetaProperty().getName() : null;
    if (metaPropertyPath != null && DynAttrUtils.isDynamicAttributeProperty(propertyName)) {
        String attributeCode = DynAttrUtils.getAttributeCodeFromProperty(propertyName);
        getDynAttrMetadata().getAttributes(metaPropertyPath.getMetaClass()).stream().filter(attr -> Objects.equals(attributeCode, attr.getCode())).findFirst().ifPresent(attr -> {
            field.setCaption(getMessageBundleTools().getLocalizedValue(attr.getNameMsgBundle(), attr.getName()));
            field.setDescription(getMessageBundleTools().getLocalizedValue(attr.getDescriptionsMsgBundle(), attr.getDescription()));
        });
    } else {
        loadCaption(field, element);
        if (field.getCaption() == null) {
            field.setCaption(getDefaultCaption(field, targetDs));
        }
    }
    loadDescription(field, element);
    loadContextHelp(field, element);
    field.setXmlDescriptor(element);
    Formatter formatter = loadFormatter(element);
    if (formatter != null) {
        field.setFormatter(formatter);
    }
    String defaultWidth = element.attributeValue("width");
    if (StringUtils.isEmpty(defaultWidth)) {
        defaultWidth = columnWidth;
    }
    loadWidth(field, defaultWidth);
    if (customField) {
        field.setCustom(true);
    }
    String required = element.attributeValue("required");
    if (StringUtils.isNotEmpty(required)) {
        field.setRequired(Boolean.parseBoolean(required));
    }
    String requiredMsg = element.attributeValue("requiredMessage");
    if (requiredMsg != null) {
        requiredMsg = loadResourceString(requiredMsg);
        field.setRequiredMessage(requiredMsg);
    }
    String tabIndex = element.attributeValue("tabIndex");
    if (StringUtils.isNotEmpty(tabIndex)) {
        field.setTabIndex(Integer.parseInt(tabIndex));
    }
    loadInputPrompt(field, element);
    if (customElements.size() == 1) {
        // load nested component defined as inline
        Element customFieldElement = customElements.get(0);
        LayoutLoader loader = getLayoutLoader();
        ComponentLoader childComponentLoader = loader.createComponent(customFieldElement);
        childComponentLoader.loadComponent();
        Component customComponent = childComponentLoader.getResultComponent();
        String inlineAttachMode = element.attributeValue("inlineAttachMode");
        if (StringUtils.isNotEmpty(inlineAttachMode)) {
            field.setComponent(customComponent, FieldGroup.FieldAttachMode.valueOf(inlineAttachMode));
        } else {
            field.setComponent(customComponent);
        }
    }
    return field;
}
Also used : Datasource(com.haulmont.cuba.gui.data.Datasource) EmbeddedDatasource(com.haulmont.cuba.gui.data.EmbeddedDatasource) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) Iterables(com.google.common.collect.Iterables) MetaClass(io.jmix.core.metamodel.model.MetaClass) java.util(java.util) FieldGroupFieldFactory(com.haulmont.cuba.gui.components.FieldGroupFieldFactory) Datasource(com.haulmont.cuba.gui.data.Datasource) DynamicAttributesGuiTools(com.haulmont.cuba.gui.dynamicattributes.DynamicAttributesGuiTools) Formatter(io.jmix.ui.component.formatter.Formatter) ComponentLoader(io.jmix.ui.xml.layout.ComponentLoader) Security(com.haulmont.cuba.core.global.Security) ComponentLoaderHelper(com.haulmont.cuba.gui.xml.data.ComponentLoaderHelper) MetaPropertyPath(io.jmix.core.metamodel.model.MetaPropertyPath) DynAttrMetadata(io.jmix.dynattr.DynAttrMetadata) Frame(io.jmix.ui.component.Frame) BooleanUtils(org.apache.commons.lang3.BooleanUtils) StringUtils(org.apache.commons.lang3.StringUtils) EntityOp(io.jmix.core.security.EntityOp) Strings(com.google.common.base.Strings) Component(io.jmix.ui.component.Component) LayoutLoader(io.jmix.ui.xml.layout.loader.LayoutLoader) EmbeddedDatasource(com.haulmont.cuba.gui.data.EmbeddedDatasource) MetadataTools(io.jmix.core.MetadataTools) FieldGroup(com.haulmont.cuba.gui.components.FieldGroup) DsContext(com.haulmont.cuba.gui.data.DsContext) Nullable(javax.annotation.Nullable) LegacyFrame(com.haulmont.cuba.gui.screen.compatibility.LegacyFrame) DynAttrUtils(io.jmix.dynattr.DynAttrUtils) Screen(io.jmix.ui.screen.Screen) DeclarativeFieldGenerator(com.haulmont.cuba.gui.xml.DeclarativeFieldGenerator) Collectors(java.util.stream.Collectors) UiControllerUtils(io.jmix.ui.screen.UiControllerUtils) Consumer(java.util.function.Consumer) GuiDevelopmentException(io.jmix.ui.GuiDevelopmentException) AttributeDefinition(io.jmix.dynattr.AttributeDefinition) MsgBundleTools(io.jmix.dynattr.MsgBundleTools) EntityAttrAccess(com.haulmont.cuba.security.entity.EntityAttrAccess) FieldCaptionAlignment(com.haulmont.cuba.gui.components.FieldGroup.FieldCaptionAlignment) Element(org.dom4j.Element) UiComponents(com.haulmont.cuba.gui.UiComponents) MetaProperty(io.jmix.core.metamodel.model.MetaProperty) MessageTools(io.jmix.core.MessageTools) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) LayoutLoader(io.jmix.ui.xml.layout.loader.LayoutLoader) DsContext(com.haulmont.cuba.gui.data.DsContext) FieldGroup(com.haulmont.cuba.gui.components.FieldGroup) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) Formatter(io.jmix.ui.component.formatter.Formatter) Element(org.dom4j.Element) LegacyFrame(com.haulmont.cuba.gui.screen.compatibility.LegacyFrame) MetaPropertyPath(io.jmix.core.metamodel.model.MetaPropertyPath) ComponentLoader(io.jmix.ui.xml.layout.ComponentLoader) MetaClass(io.jmix.core.metamodel.model.MetaClass) GuiDevelopmentException(io.jmix.ui.GuiDevelopmentException) Component(io.jmix.ui.component.Component)

Example 5 with Formatter

use of io.jmix.ui.component.formatter.Formatter in project jmix by jmix-framework.

the class AbstractTable method formatCellValue.

@Nullable
protected String formatCellValue(Object rowId, Object colId, @Nullable Property<?> property) {
    TableItems<E> tableItems = getItems();
    if (tableItems == null || tableItems.getState() == BindingState.INACTIVE) {
        return null;
    }
    Column<E> column = columns.get(colId);
    if (column != null && column.getValueProvider() != null) {
        E item = tableItems.getItem(rowId);
        Object generatedValue = column.getValueProvider().apply(item);
        Formatter formatter = column.getFormatter();
        if (formatter != null) {
            return (String) formatter.apply(generatedValue);
        }
        return metadataTools.format(generatedValue);
    }
    Object cellValue;
    if (ignoreUnfetchedAttributes && colId instanceof MetaPropertyPath) {
        E item = tableItems.getItem(rowId);
        cellValue = getValueExIgnoreUnfetched(item, ((MetaPropertyPath) colId).getPath());
    } else if (property != null) {
        cellValue = property.getValue();
    } else {
        cellValue = null;
    }
    if (colId instanceof MetaPropertyPath) {
        MetaPropertyPath propertyPath = (MetaPropertyPath) colId;
        if (column != null) {
            if (column.getFormatter() != null) {
                return (String) column.getFormatter().apply(cellValue);
            } else if (column.getXmlDescriptor() != null) {
                // vaadin8 move to Column
                String captionProperty = column.getXmlDescriptor().attributeValue("captionProperty");
                if (StringUtils.isNotEmpty(captionProperty)) {
                    E item = getItems().getItemNN(rowId);
                    Object captionValue = EntityValues.getValueEx(item, captionProperty);
                    return captionValue != null ? String.valueOf(captionValue) : null;
                }
            }
        }
        return metadataTools.format(cellValue, propertyPath.getMetaProperty());
    }
    if (cellValue == null) {
        return "";
    }
    if (!(cellValue instanceof Component)) {
        return metadataTools.format(cellValue);
    }
    // fallback to Vaadin formatting
    UI ui = component.getUI();
    VaadinSession session = ui != null ? ui.getSession() : null;
    Converter converter = ConverterUtil.getConverter(String.class, property.getType(), session);
    if (converter != null) {
        return (String) converter.convertToPresentation(cellValue, String.class, locale);
    }
    return cellValue.toString();
}
Also used : AppUI(io.jmix.ui.AppUI) VaadinSession(com.vaadin.server.VaadinSession) Formatter(io.jmix.ui.component.formatter.Formatter) MetaPropertyPath(io.jmix.core.metamodel.model.MetaPropertyPath) Converter(com.vaadin.v7.data.util.converter.Converter) AbstractComponent(com.vaadin.ui.AbstractComponent) Component(com.vaadin.ui.Component) Nullable(javax.annotation.Nullable)

Aggregations

Formatter (io.jmix.ui.component.formatter.Formatter)6 GuiDevelopmentException (io.jmix.ui.GuiDevelopmentException)4 Element (org.dom4j.Element)4 Nullable (javax.annotation.Nullable)3 Strings (com.google.common.base.Strings)2 MetaPropertyPath (io.jmix.core.metamodel.model.MetaPropertyPath)2 AttributeDefinition (io.jmix.dynattr.AttributeDefinition)2 MsgBundleTools (io.jmix.dynattr.MsgBundleTools)2 Iterables (com.google.common.collect.Iterables)1 Security (com.haulmont.cuba.core.global.Security)1 UiComponents (com.haulmont.cuba.gui.UiComponents)1 FieldGroup (com.haulmont.cuba.gui.components.FieldGroup)1 FieldCaptionAlignment (com.haulmont.cuba.gui.components.FieldGroup.FieldCaptionAlignment)1 FieldGroupFieldFactory (com.haulmont.cuba.gui.components.FieldGroupFieldFactory)1 CollectionDatasource (com.haulmont.cuba.gui.data.CollectionDatasource)1 Datasource (com.haulmont.cuba.gui.data.Datasource)1 DsContext (com.haulmont.cuba.gui.data.DsContext)1 EmbeddedDatasource (com.haulmont.cuba.gui.data.EmbeddedDatasource)1 DynamicAttributesGuiTools (com.haulmont.cuba.gui.dynamicattributes.DynamicAttributesGuiTools)1 LegacyFrame (com.haulmont.cuba.gui.screen.compatibility.LegacyFrame)1