/** Colore les champs en rouge si erreur * @param validate */ @SuppressWarnings("unchecked") private void validateFields(Boolean validate){ listLayoutTraductions.forEach(e -> { AbstractField<String> tf; if (e.getComponent(0) instanceof TextField || e.getComponent(0) instanceof RichTextArea){ tf = (AbstractField<String>) e.getComponent(0); }else if (e.getComponent(0) instanceof HorizontalLayout){ tf = (AbstractField<String>) e.getComponent(1); }else{ tf = (AbstractField<String>) e.getComponent(1); } /* Ajout du style*/ if (validate){ tf.removeStyleName(StyleConstants.FIELD_ERROR_COMPLETE); }else{ tf.addStyleName(StyleConstants.FIELD_ERROR_COMPLETE); } }); }
private boolean findFieldAndFocus(Component compositionRoot) { if (compositionRoot instanceof AbstractComponentContainer) { AbstractComponentContainer cc = (AbstractComponentContainer) compositionRoot; for (Component component : cc) { if (component instanceof AbstractTextField) { AbstractTextField abstractTextField = (AbstractTextField) component; abstractTextField.selectAll(); return true; } if (component instanceof AbstractField) { AbstractField<?> abstractField = (AbstractField<?>) component; abstractField.focus(); return true; } if (component instanceof AbstractComponentContainer) { if (findFieldAndFocus(component)) { return true; } } } } return false; }
protected void addComponentListeners() { // avoid duplicate registration removeListeners(); for (final AbstractField<?> field : allComponents) { if (field instanceof TextChangeNotifier) { ((TextChangeNotifier) field).addTextChangeListener(new ChangeListener(field)); } if (field instanceof Table) { ((Table) field).addItemSetChangeListener(new ChangeListener(field)); } field.addValueChangeListener(new ChangeListener(field)); } }
private static List<AbstractField<?>> getAllComponents(final AbstractLayout abstractLayout) { final List<AbstractField<?>> components = new ArrayList<>(); final Iterator<Component> iterate = abstractLayout.iterator(); while (iterate.hasNext()) { final Component c = iterate.next(); if (c instanceof AbstractLayout) { components.addAll(getAllComponents((AbstractLayout) c)); } if (c instanceof AbstractField) { components.add((AbstractField<?>) c); } if (c instanceof FlexibleOptionGroupItemComponent) { components.add(((FlexibleOptionGroupItemComponent) c).getOwner()); } if (c instanceof TabSheet) { final TabSheet tabSheet = (TabSheet) c; components.addAll(getAllComponentsFromTabSheet(tabSheet)); } } return components; }
@Override public void setPersisted(ET v, boolean persisted) { int row = itemsIdentityIndexOf(v) + 1; if (isAllowRemovingItems()) { Button c = (Button) layout.getComponent(layout.getColumns() - 1, row); if (persisted) { c.setDescription(getDeleteElementDescription()); } else { for (int i = 0; i < getVisibleProperties().size(); i++) { try { AbstractField f = (AbstractField) layout. getComponent(i, row); // FIXME //f.setValidationVisible(false); } catch (Exception e) { } } c.setDescription(getDisabledDeleteElementDescription()); } c.setEnabled(persisted); } }
@Test public void testAddStateChangeWrapper() { assertNull(viewModelComposer.addStateChangeWrapper(AbstractField.class, new StateChangeWrapper() { @Override public StateChangeListener getStateChangeListener( final Object notified) { return new StateChangeListener() { @SuppressWarnings("unchecked") @Override public void stateChange(Object value) { ((AbstractField<Object>) notified) .setValue(value); } }; } })); }
@Test public void testRequiredIndicatorVisible() { AbstractField<String> field = mock(TextField.class); EasyBinding<?,?,?> binding = binder.bind(field, "testIntMin1", new StringToIntegerConverter("")); assertNotNull(binding); verify(field, times(1)).setRequiredIndicatorVisible(true); }
@Test public void testRequiredIndicatorNotVisible() { AbstractField<String> field = mock(TextField.class); EasyBinding<?,?,?> binding = binder.bind(field, "testIntMin0", new StringToIntegerConverter("")); assertNotNull(binding); verify(field, never()).setRequiredIndicatorVisible(true); }
@Test public void testRequiredIndicatorNotVisibleNoAnnotation() { AbstractField<String> field = mock(TextField.class); EasyBinding<?,?,?> binding = binder.bind(field, "testInt", new StringToIntegerConverter("")); assertNotNull(binding); verify(field, never()).setRequiredIndicatorVisible(true); }
@Test public void testRequiredIndicatorVisibleCustomIndicator() { AbstractField<String> field = mock(TextField.class); binder.setRequiredConfigurator(e -> true); assertNotNull(binder.getRequiredConfigurator()); EasyBinding<?,?,?> binding = binder.bind(field, "testIntMin0", new StringToIntegerConverter("")); assertNotNull(binding); verify(field, times(1)).setRequiredIndicatorVisible(true); }
@SuppressWarnings("unchecked") @Test public void testBuildAndBind() { AutoBinder<MyEntity> binder = new AutoBinder<>(MyEntity.class); binder.buildAndBind("car", "car.frontLeft", "car.frontLeft.tire", "spare", "spare.tire"); MyEntity entity = new MyEntity(); binder.setBean(entity); assertTrue(binder.getFieldForProperty("street").isPresent()); assertTrue(binder.getFieldForProperty("number").isPresent()); assertTrue(binder.getFieldForProperty("number2").isPresent()); assertTrue(binder.getFieldForProperty("car.frontLeft.tire.type").isPresent()); assertTrue(binder.getFieldForProperty("spare.tire.type").isPresent()); assertTrue(binder.getFieldForProperty("unknown").isPresent()); AbstractField<String> numberField = (AbstractField<String>) binder.getFieldForProperty("number").get(); AbstractField<String> numberField2 = (AbstractField<String>) binder.getFieldForProperty("number2").get(); ((HasValue<String>) binder.getFieldForProperty("street").get()).setValue("mystreet"); assertEquals("mystreet", entity.getStreet()); numberField.setValue("100"); assertEquals(new Integer(100), entity.getNumber()); assertNull(numberField.getComponentError()); numberField.setValue("0"); assertNotNull(numberField.getComponentError()); numberField.setValue(""); assertEquals(null, entity.getNumber()); assertNull(numberField.getComponentError()); numberField2.setValue(""); assertNotNull(numberField2.getComponentError()); }
/** Renvoie un layout contenant un choix de langue et une traduction * @param traductionOther * @return le layout */ private HorizontalLayout getLangueLayout(I18nTraduction traductionOther){ /*Le layout renvoyé*/ HorizontalLayout hlLangueOther = new HorizontalLayout(); listLayoutTraductions.add(hlLangueOther); hlLangueOther.setSpacing(true); hlLangueOther.setWidth(100, Unit.PERCENTAGE); /*La combobox avec les icones de drapeaux*/ ComboBoxLangue cbLangue = new ComboBoxLangue(listeLangueEnService,false); cbLangue.selectLangue((traductionOther==null?null:traductionOther.getLangue())); cbLangue.setWidth(75, Unit.PIXELS); hlLangueOther.addComponent(cbLangue); /*Le textField... ou */ AbstractField<String> tfValOther = getNewValueComponent(); tfValOther.setWidth(100, Unit.PERCENTAGE); if (traductionOther!=null){ tfValOther.setValue(traductionOther.getValTrad()); } hlLangueOther.addComponent(tfValOther); hlLangueOther.setExpandRatio(tfValOther,1); /*Le bouton de suppression de la langue*/ OneClickButton removeLangue = new OneClickButton(FontAwesome.MINUS_SQUARE_O); removeLangue.addStyleName(ValoTheme.BUTTON_ICON_ONLY); removeLangue.addStyleName(ValoTheme.BUTTON_BORDERLESS); removeLangue.addClickListener(e->{layoutLangue.removeComponent(hlLangueOther);listLayoutTraductions.remove(hlLangueOther);checkVisibleAddLangue();centerWindow();}); hlLangueOther.addComponent(removeLangue); return hlLangueOther; }
@SuppressWarnings("unchecked") private void substract(Component c, int value) { if (c instanceof AbstractField) { ((AbstractField<Integer>) c).setValue(((AbstractField<Integer>) c).getValue() - value); } else if (c instanceof Label) { ((Label) c).setValue(String.valueOf(Integer.parseInt(((Label) c).getValue()) - value)); } }
@SuppressWarnings("unchecked") private void add(Component c, int value) { if (c instanceof AbstractField) { ((AbstractField<Integer>) c).setValue(((AbstractField<Integer>) c).getValue() + value); } else if (c instanceof Label) { ((Label) c).setValue(String.valueOf(Integer.parseInt(((Label) c).getValue()) + value)); } }
private void removeListeners() { for (final AbstractField<?> field : allComponents) { removeTextListener(field); removeValueChangeListener(field); removeItemSetChangeistener(field); } }
private void removeItemSetChangeistener(final AbstractField<?> field) { if (!(field instanceof Table)) { return; } for (final Object listener : field.getListeners(ItemSetChangeEvent.class)) { if (listener instanceof ChangeListener) { ((Table) field).removeItemSetChangeListener((ChangeListener) listener); } } }
private void removeTextListener(final AbstractField<?> field) { if (!(field instanceof TextChangeNotifier)) { return; } for (final Object listener : field.getListeners(TextChangeEvent.class)) { if (listener instanceof ChangeListener) { ((TextChangeNotifier) field).removeTextChangeListener((ChangeListener) listener); } } }
private void removeValueChangeListener(final AbstractField<?> field) { for (final Object listener : field.getListeners(ValueChangeEvent.class)) { if (listener instanceof ChangeListener) { field.removeValueChangeListener((ChangeListener) listener); } } }
/** * saves the original values in a Map so we can use them for detecting * changes */ public final void setOrginaleValues() { for (final AbstractField<?> field : allComponents) { Object value = field.getValue(); if (field instanceof Table) { value = ((Table) field).getContainerDataSource().getItemIds(); } orginalValues.put(field, value); } saveButton.setEnabled(isSaveButtonEnabledAfterValueChange(null, null)); }
private boolean isValuesChanged(final Component currentChangedComponent, final Object newValue) { for (final AbstractField<?> field : allComponents) { Object originalValue = orginalValues.get(field); if (field instanceof CheckBox && originalValue == null) { originalValue = Boolean.FALSE; } final Object currentValue = getCurrentVaue(currentChangedComponent, newValue, field); if (!Objects.equals(originalValue, currentValue)) { return true; } } return false; }
private static Object getCurrentVaue(final Component currentChangedComponent, final Object newValue, final AbstractField<?> field) { Object currentValue = field.getValue(); if (field instanceof Table) { currentValue = ((Table) field).getContainerDataSource().getItemIds(); } if (field.equals(currentChangedComponent)) { currentValue = newValue; } return currentValue; }
private boolean shouldMandatoryLabelShown() { for (final AbstractField<?> field : allComponents) { if (field.isRequired()) { return true; } } return false; }
private boolean isMandatoryFieldNotEmptyAndValid(final Component currentChangedComponent, final Object newValue) { boolean valid = true; final List<AbstractField<?>> requiredComponents = allComponents.stream().filter(AbstractField::isRequired) .filter(AbstractField::isEnabled).collect(Collectors.toList()); requiredComponents.addAll(allComponents.stream().filter(this::hasNullValidator).collect(Collectors.toList())); for (final AbstractField field : requiredComponents) { Object value = getCurrentVaue(currentChangedComponent, newValue, field); if (String.class.equals(field.getType())) { value = Strings.emptyToNull((String) value); } if (Set.class.equals(field.getType())) { value = emptyToNull((Collection<?>) value); } if (value == null) { return false; } // We need to loop through the entire loop for validity testing. // Otherwise the UI will only mark the // first field with errors and then stop. If there are several // fields with errors, this is bad. field.setValue(value); if (!field.isValid()) { valid = false; } } return valid; }
private boolean hasNullValidator(final Component component) { if (component instanceof AbstractField<?>) { final AbstractField<?> fieldComponent = (AbstractField<?>) component; for (final Validator validator : fieldComponent.getValidators()) { if (validator instanceof NullValidator) { return true; } } } return false; }
private static List<AbstractField<?>> getAllComponentsFromTabSheet(final TabSheet tabSheet) { final List<AbstractField<?>> components = new ArrayList<>(); for (final Iterator<Component> i = tabSheet.iterator(); i.hasNext();) { final Component component = i.next(); if (component instanceof AbstractLayout) { components.addAll(getAllComponents((AbstractLayout) component)); } } return components; }
/** * @return */ private ClickListener getSubmitButtonClickListener() { return new Button.ClickListener() { /** * */ private static final long serialVersionUID = 4846553077403712887L; @Override public void buttonClick(ClickEvent event) { try { fieldGroup.commit(); } catch (CommitException e) { Map<Field<?>, InvalidValueException> invalidFields = e .getInvalidFields(); // TODO handle it in a better way for (Map.Entry<Field<?>, InvalidValueException> invalidField : invalidFields .entrySet()) { ((AbstractField<?>) invalidField.getKey()) .setValidationVisible(true); } if (invalidFields.isEmpty()) { // TODO Handle this error e.printStackTrace(); Notification.show("Save failed, Please try again"); } } } }; }
private void reset(final AbstractField<?> next) { assert null != next : "Parameter 'next' of method 'reset' must not be null"; if (UI.getCurrent().isAttached()) { UI.getCurrent().access(() -> (resetAbstractField(next))); //NOPMD } }
private void resetAbstractField(final AbstractField<?> next) { if (next instanceof AbstractTextField) { ((AbstractTextField) next).setValue(Constants.EMPTY); } else { next.setValue(null); } }
protected void addProfileInputField(GridLayout layout, String name, AbstractField inputField, String inputFieldValue) { Label label = new Label(name + ": "); label.addStyleName(ExplorerLayout.STYLE_PROFILE_FIELD); label.setSizeUndefined(); layout.addComponent(label); layout.setComponentAlignment(label, Alignment.MIDDLE_LEFT); if (inputFieldValue != null) { inputField.setValue(inputFieldValue); } layout.addComponent(inputField); layout.setComponentAlignment(inputField, Alignment.MIDDLE_LEFT); }
private static AbstractField<?> findAbstractField(Component c) { if (c instanceof AbstractField) { return ((AbstractField<?>) c); } else if (c instanceof ComponentContainer) { ComponentContainer container = (ComponentContainer) c; Iterator<Component> components = container.iterator(); while (components.hasNext()) { AbstractField<?> field = findAbstractField(components.next()); if (field != null) { return field; } } } return null; }
protected AbstractField<?> addSetting(String text, String globalSetting, String defaultValue, String description, Class<?> converter) { final GlobalSetting setting = getGlobalSetting(globalSetting, defaultValue); AbstractField<?> field = null; if (Boolean.class.equals(converter)) { final CheckBox checkbox = new CheckBox(text); checkbox.setImmediate(true); checkbox.setValue(Boolean.parseBoolean(setting.getValue())); checkbox.addValueChangeListener( (e) -> saveSetting(setting, checkbox.getValue().toString())); field = checkbox; } else { field = new ImmediateUpdateTextField(text) { protected void save(String value) { saveSetting(setting, value); } }; field.setDescription(description); ((ImmediateUpdateTextField) field).setValue(setting.getValue()); if (converter != null) { field.setConverter(converter); } } form.addComponent(field); return field; }
/** * Bind an existing field to a propertyId * * If the caption of the field is null, it will be auto-generated */ public <T extends Field<?>> T bind(T field, Object propertyId) { try { Class<?> dataType = getPropertyType(propertyId); propertyIdToType.put(propertyId, dataType); propertyIdToField.put(propertyId, field); fieldToPropertyId.put(field, propertyId); if (field instanceof AbstractField<?>) { ((AbstractField) field).setValidationVisible(false); } if (field instanceof CollectionTable) { collectionFields.put(propertyId, (CollectionTable<?, ?>) field); } if (hasItemDataSource()) getFieldGroup().bind(field, propertyId); // FIXME this is quite a side-effect. Verify if it makes sense to remove it if (field.getCaption() == null) { field.setCaption(createCaptionByPropertyId(propertyId)); } configureField(field); return field; } catch (RuntimeException e) { throw new FieldGroup.BindException("Could not bind field "+field.getClass().getCanonicalName()+" to property "+propertyId, e); } }
/** * Unbind the given field from the data source */ public void unbind(Field<?> field) { if (hasItemDataSource()) getFieldGroup().unbind(field); if (field instanceof AbstractField<?>) { ((AbstractField) field).setValidationVisible(false); } field.setPropertyDataSource(null); resetField(field); configureField(field); }
private boolean findFieldAndFocus(Component compositionRoot) { if (compositionRoot instanceof AbstractComponentContainer) { AbstractComponentContainer cc = (AbstractComponentContainer) compositionRoot; for (Component component : cc) { if (component instanceof AbstractTextField) { AbstractTextField abstractTextField = (AbstractTextField) component; if (!abstractTextField.isReadOnly()) { abstractTextField.selectAll(); return true; } } if (component instanceof AbstractField) { AbstractField abstractField = (AbstractField) component; if (!abstractField.isReadOnly()) { abstractField.focus(); return true; } } if (component instanceof AbstractComponentContainer) { if (findFieldAndFocus(component)) { return true; } } } } return false; }
/** * Allows you to provide a custom filtering field for the properties as * needed. * * @param propertyId ID of the property for for which the field is asked for * @return a custom filtering field OR null if you want to use the generated * default field. */ @Override public AbstractField<?> getCustomFilterComponent(final Object propertyId) { AbstractField<?> field = null; for (final FilterGenerator generator : generators) { field = generator.getCustomFilterComponent(propertyId); if(field != null) return field; } return field; }
/** * Set common fields properties * * @param component * @param element * @param properties * @param alignmentWrapper */ @SuppressWarnings("rawtypes") public static void setCommonFieldProperties(AbstractField component, Element element, Map<String, String> properties, AlignmentWrapper alignmentWrapper) { setCommonProperties(component, element, properties, alignmentWrapper); // set AbstractField specific properties component .setReadOnly(ConversionUtility.getBooleanOrDefault(properties.get(DocumentConstants.READ_ONLY), false)); }
@SuppressWarnings("rawtypes") private void addValueChangeListeners(AbstractField c) { for (ValueChangeListener listener : valueChangeListeners) { c.addValueChangeListener(listener); } }
public void addComponent(AbstractField<?> field) { HorizontalLayout line = new HorizontalLayout(); Label label = new Label(field.getCaption()); label.setWidth("" + this.labelWidth); line.addComponent(label); field.setWidth("" + fieldWidth); field.setImmediate(true); line.addComponent(field); field.setCaption(null); Label errorLabel = new Label(); errorLabel.setContentMode(ContentMode.HTML); line.addComponent(errorLabel); addDynamicValidation(field); fields.add(new FieldPair(field, errorLabel)); // The first field added to the form is given focus. if (fields.size() == 1) field.focus(); this.addComponent(line); }
private void addDynamicValidation(AbstractField<?> field) { if (field instanceof AbstractTextField) { ((AbstractTextField) field).addTextChangeListener(listener -> { validate(field); }); ((AbstractTextField) field).addBlurListener(listener -> { validate(field); }); } else if (field instanceof ComboBox) { ((ComboBox) field).addBlurListener(listener -> { validate(field); }); field.addValueChangeListener(listener -> { validate(field); }); } else { field.addValueChangeListener(listener -> { validate(field); }); } }