Here are the examples of the java api com.vaadin.flow.data.binder.Binder taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
7 Examples
19
Source : ApplayoutDemoView.java
with Apache License 2.0
from FlowingCode
with Apache License 2.0
from FlowingCode
private void openSettings() {
Dialog dialog = new Dialog();
H3 replacedle = new H3("Demo settings");
replacedle.getStyle().set("margin-top", "0");
dialog.add(replacedle);
Checkbox cbMenuVisible = new Checkbox("Menu visible");
Checkbox cbSwipeOpen = new Checkbox("Swipe Open");
Checkbox cbFixed = new Checkbox("Fixed");
Checkbox cbReveals = new Checkbox("Reveals");
Checkbox cbCompact = new Checkbox("Compact");
cbMenuVisible.getElement().setAttribute("replacedle", "Toggle visibility of the hamburguer icon.");
cbSwipeOpen.getElement().setAttribute("replacedle", "When enabled, you can open the menu by swiping the left border of the screen.");
cbFixed.getElement().setAttribute("replacedle", "When enabled, the header is fixed at the top so it never moves away.");
cbReveals.getElement().setAttribute("replacedle", "When enabled, the header slides back when scrolling back up.");
cbCompact.getElement().setAttribute("replacedle", "When enabled, the height of the header is set to 32px.");
Binder<DemoSettings> binder = new Binder<>();
binder.forField(cbMenuVisible).bind(DemoSettings::isMenuVisible, DemoSettings::setMenuVisible);
binder.forField(cbSwipeOpen).bind(DemoSettings::isSwipeOpen, DemoSettings::setSwipeOpen);
binder.forField(cbFixed).bind(DemoSettings::isFixed, DemoSettings::setFixed);
binder.forField(cbReveals).bind(DemoSettings::isReveals, DemoSettings::setReveals);
binder.forField(cbCompact).bind(DemoSettings::isCompact, DemoSettings::setCompact);
binder.setBean(this.settings);
VerticalLayout content = new VerticalLayout(cbMenuVisible, cbSwipeOpen, cbFixed, cbReveals, cbCompact);
content.setSpacing(false);
HorizontalLayout buttons = new HorizontalLayout();
Button btnOk = new Button("OK", ev -> {
applySettings();
dialog.close();
});
Button btnCancel = new Button("Cancel", ev -> dialog.close());
btnOk.getElement().setAttribute("theme", "primary");
buttons.setSpacing(true);
buttons.add(btnOk, btnCancel);
buttons.setSpacing(true);
dialog.add(content, buttons);
dialog.setSizeUndefined();
dialog.open();
}
19
Source : AbstractAutoGeneratedCrudFormFactory.java
with Apache License 2.0
from alejandro-du
with Apache License 2.0
from alejandro-du
/**
* @author Alejandro Duarte.
*/
public abstract clreplaced AbstractAutoGeneratedCrudFormFactory<T> extends AbstractCrudFormFactory<T> {
protected Map<CrudOperation, String> buttonCaptions = new HashMap<>();
protected Map<CrudOperation, Icon> buttonIcons = new HashMap<>();
protected Map<CrudOperation, Set<String>> buttonStyleNames = new HashMap<>();
protected Map<CrudOperation, String> buttonThemes = new HashMap<>();
protected String cancelButtonCaption = "Cancel";
protected String validationErrorMessage = "Please fix the errors and try again";
protected Clreplaced<T> domainType;
protected SerializableSupplier<T> newInstanceSupplier;
protected Binder<T> binder;
public AbstractAutoGeneratedCrudFormFactory(Clreplaced<T> domainType) {
this.domainType = domainType;
setButtonCaption(CrudOperation.READ, "Ok");
setButtonCaption(CrudOperation.ADD, "Add");
setButtonCaption(CrudOperation.UPDATE, "Update");
setButtonCaption(CrudOperation.DELETE, "Yes, delete");
setButtonIcon(CrudOperation.READ, null);
setButtonIcon(CrudOperation.ADD, VaadinIcon.CHECK.create());
setButtonIcon(CrudOperation.UPDATE, VaadinIcon.CHECK.create());
setButtonIcon(CrudOperation.DELETE, VaadinIcon.TRASH.create());
addButtonStyleName(CrudOperation.READ, null);
addButtonTheme(CrudOperation.ADD, "primary");
addButtonTheme(CrudOperation.UPDATE, "primary");
addButtonTheme(CrudOperation.DELETE, "error");
setVisibleProperties(discoverProperties().toArray(new String[0]));
}
@Override
public void setNewInstanceSupplier(SerializableSupplier<T> newInstanceSupplier) {
this.newInstanceSupplier = newInstanceSupplier;
}
@Override
public SerializableSupplier<T> getNewInstanceSupplier() {
if (newInstanceSupplier == null) {
newInstanceSupplier = () -> {
try {
return domainType.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
return null;
}
};
}
return newInstanceSupplier;
}
public void setButtonCaption(CrudOperation operation, String caption) {
buttonCaptions.put(operation, caption);
}
public void setButtonIcon(CrudOperation operation, Icon icon) {
buttonIcons.put(operation, icon);
}
public void addButtonStyleName(CrudOperation operation, String styleName) {
buttonStyleNames.putIfAbsent(operation, new HashSet<>());
buttonStyleNames.get(operation).add(styleName);
}
public void addButtonTheme(CrudOperation operation, String theme) {
buttonThemes.put(operation, theme);
}
public void setCancelButtonCaption(String cancelButtonCaption) {
this.cancelButtonCaption = cancelButtonCaption;
}
public void setValidationErrorMessage(String validationErrorMessage) {
this.validationErrorMessage = validationErrorMessage;
}
protected List<String> discoverProperties() {
try {
List<PropertyDescriptor> descriptors = BeanUtil.getBeanPropertyDescriptors(domainType);
return descriptors.stream().filter(d -> !d.getName().equals("clreplaced")).map(d -> d.getName()).collect(Collectors.toList());
} catch (IntrospectionException e) {
throw new RuntimeException(e);
}
}
protected List<HasValueAndElement> buildFields(CrudOperation operation, T domainObject, boolean readOnly) {
binder = buildBinder(operation, domainObject);
ArrayList<HasValueAndElement> fields = new ArrayList<>();
CrudFormConfiguration configuration = getConfiguration(operation);
boolean focused = false;
ArrayList<HasValueAndElement> fieldsWithCreationListeners = new ArrayList<>();
ArrayList<FieldCreationListener> creationListeners = new ArrayList<>();
for (int i = 0; i < configuration.getVisibleProperties().size(); i++) {
String property = configuration.getVisibleProperties().get(i);
try {
String fieldCaption = null;
if (!configuration.getFieldCaptions().isEmpty()) {
fieldCaption = configuration.getFieldCaptions().get(i);
}
Clreplaced<?> propertyType = BeanUtil.getPropertyType(domainObject.getClreplaced(), property);
if (propertyType != null) {
HasValueAndElement field = buildField(configuration, property, propertyType);
if (field != null) {
configureField(field, property, fieldCaption, readOnly, configuration);
bindField(field, property, propertyType, configuration);
fields.add(field);
if (!focused) {
if (field.isEnabled() && !field.isReadOnly() && field instanceof Focusable) {
((Focusable) field).focus();
focused = true;
}
}
FieldCreationListener creationListener = configuration.getFieldCreationListeners().get(property);
if (creationListener != null) {
fieldsWithCreationListeners.add(field);
creationListeners.add(creationListener);
}
}
}
} catch (Exception e) {
throw new RuntimeException("Error creating Field for property " + domainObject.getClreplaced().getName() + "." + property, e);
}
}
binder.readBean(domainObject);
for (int i = 0; i < fieldsWithCreationListeners.size(); i++) {
creationListeners.get(i).fieldCreated(fieldsWithCreationListeners.get(i));
}
if (!fields.isEmpty() && !readOnly) {
HasValue field = fields.get(0);
if (field instanceof Focusable) {
((Focusable) field).focus();
}
}
return fields;
}
protected HasValueAndElement buildField(CrudFormConfiguration configuration, String property, Clreplaced<?> propertyType) throws InstantiationException, IllegalAccessException {
HasValueAndElement<?, ?> field;
FieldProvider<?, ?> provider = configuration.getFieldProviders().get(property);
if (provider != null) {
field = provider.buildField();
} else {
Clreplaced<? extends HasValueAndElement<?, ?>> fieldType = configuration.getFieldTypes().get(property);
if (fieldType != null) {
field = fieldType.newInstance();
} else {
field = new DefaultFieldProvider(propertyType).buildField();
}
}
return field;
}
private void configureField(HasValue field, String property, String fieldCaption, boolean readOnly, CrudFormConfiguration configuration) {
if (fieldCaption == null) {
fieldCaption = SharedUtil.propertyIdToHumanFriendly(property);
}
try {
Method setLabelMethod = field.getClreplaced().getMethod("setLabel", String.clreplaced);
setLabelMethod.invoke(field, fieldCaption);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignore) {
}
if (field != null && field instanceof Hreplacedize) {
((Hreplacedize) field).setWidth("100%");
}
field.setReadOnly(readOnly);
if (!configuration.getDisabledProperties().isEmpty() && field instanceof HasEnabled) {
((HasEnabled) field).setEnabled(!configuration.getDisabledProperties().contains(property));
}
}
protected void bindField(HasValue field, String property, Clreplaced<?> propertyType, CrudFormConfiguration configuration) {
Binder.BindingBuilder bindingBuilder = binder.forField(field);
if (TextField.clreplaced.isreplacedignableFrom(field.getClreplaced()) || PreplacedwordField.clreplaced.isreplacedignableFrom(field.getClreplaced()) || TextArea.clreplaced.isreplacedignableFrom(field.getClreplaced())) {
bindingBuilder = bindingBuilder.withNullRepresentation("");
}
if (configuration.getConverters().containsKey(property)) {
bindingBuilder = bindingBuilder.withConverter(configuration.getConverters().get(property));
} else if (Double.clreplaced.isreplacedignableFrom(propertyType) || double.clreplaced.isreplacedignableFrom(propertyType)) {
bindingBuilder = bindingBuilder.withConverter(new StringToDoubleConverter(null, "Must be a number"));
} else if (Long.clreplaced.isreplacedignableFrom(propertyType) || long.clreplaced.isreplacedignableFrom(propertyType)) {
bindingBuilder = bindingBuilder.withConverter(new StringToLongConverter(null, "Must be a number"));
} else if (BigDecimal.clreplaced.isreplacedignableFrom(propertyType)) {
bindingBuilder = bindingBuilder.withConverter(new StringToBigDecimalConverter(null, "Must be a number"));
} else if (BigInteger.clreplaced.isreplacedignableFrom(propertyType)) {
bindingBuilder = bindingBuilder.withConverter(new StringToBigIntegerConverter(null, "Must be a number"));
} else if (Integer.clreplaced.isreplacedignableFrom(propertyType) || int.clreplaced.isreplacedignableFrom(propertyType)) {
bindingBuilder = bindingBuilder.withConverter(new StringToIntegerConverter(null, "Must be a number"));
} else if (Byte.clreplaced.isreplacedignableFrom(propertyType) || byte.clreplaced.isreplacedignableFrom(propertyType)) {
bindingBuilder = bindingBuilder.withConverter(new StringToByteConverter(null, "Must be a number"));
} else if (Character.clreplaced.isreplacedignableFrom(propertyType) || char.clreplaced.isreplacedignableFrom(propertyType)) {
bindingBuilder = bindingBuilder.withConverter(new StringToCharacterConverter());
} else if (Float.clreplaced.isreplacedignableFrom(propertyType) || float.clreplaced.isreplacedignableFrom(propertyType)) {
bindingBuilder = bindingBuilder.withConverter(new StringToFloatConverter(null, "Must be a number"));
} else if (Date.clreplaced.isreplacedignableFrom(propertyType)) {
bindingBuilder = bindingBuilder.withConverter(new LocalDateToDateConverter());
}
bindingBuilder.bind(property);
}
protected Binder<T> buildBinder(CrudOperation operation, T domainObject) {
Binder<T> binder;
if (getConfiguration(operation).isUseBeanValidation()) {
binder = new BeanValidationBinder(domainObject.getClreplaced());
} else {
binder = new Binder(domainObject.getClreplaced());
}
return binder;
}
protected Button buildOperationButton(CrudOperation operation, T domainObject, ComponentEventListener<ClickEvent<Button>> clickListener) {
if (clickListener == null) {
return null;
}
String caption = buttonCaptions.get(operation);
Icon icon = buttonIcons.get(operation);
Button button = icon != null ? new Button(caption, icon) : new Button(caption);
if (buttonStyleNames.containsKey(operation)) {
buttonStyleNames.get(operation).stream().filter(styleName -> styleName != null).forEach(styleName -> button.addClreplacedName(styleName));
}
if (buttonThemes.containsKey(operation)) {
button.getElement().setAttribute("theme", buttonThemes.get(operation));
}
button.addClickListener(event -> {
if (binder.writeBeanIfValid(domainObject)) {
try {
clickListener.onComponentEvent(event);
} catch (Exception e) {
showError(operation, e);
}
} else {
Notification.show(validationErrorMessage);
}
});
return button;
}
@Override
public void showError(CrudOperation operation, Exception e) {
if (errorListener != null) {
errorListener.accept(e);
} else {
if (CrudOperationException.clreplaced.isreplacedignableFrom(e.getClreplaced())) {
// FIXME no Notification.Type
Notification.show(e.getMessage());
} else {
Notification.show(e.getMessage());
throw new RuntimeException("Error executing " + operation.name() + " operation", e);
}
}
}
protected Button buildCancelButton(ComponentEventListener<ClickEvent<Button>> clickListener) {
if (clickListener == null) {
return null;
}
return new Button(cancelButtonCaption, clickListener);
}
protected Component buildFooter(CrudOperation operation, T domainObject, ComponentEventListener<ClickEvent<Button>> cancelButtonClickListener, ComponentEventListener<ClickEvent<Button>> operationButtonClickListener) {
Button operationButton = buildOperationButton(operation, domainObject, operationButtonClickListener);
Button cancelButton = buildCancelButton(cancelButtonClickListener);
HorizontalLayout footerLayout = new HorizontalLayout();
footerLayout.setSizeUndefined();
footerLayout.setSpacing(true);
footerLayout.setPadding(false);
if (cancelButton != null) {
footerLayout.add(cancelButton);
}
if (operationButton != null) {
footerLayout.add(operationButton);
}
return footerLayout;
}
}
19
Source : AbstractAutoGeneratedCrudFormFactory.java
with Apache License 2.0
from alejandro-du
with Apache License 2.0
from alejandro-du
protected Binder<T> buildBinder(CrudOperation operation, T domainObject) {
Binder<T> binder;
if (getConfiguration(operation).isUseBeanValidation()) {
binder = new BeanValidationBinder(domainObject.getClreplaced());
} else {
binder = new Binder(domainObject.getClreplaced());
}
return binder;
}
16
Source : ContactForm.java
with The Unlicense
from vaadin-learning-center
with The Unlicense
from vaadin-learning-center
public clreplaced ContactForm extends FormLayout {
TextField firstName = new TextField("First name");
TextField lastName = new TextField("Last name");
EmailField email = new EmailField("Email");
ComboBox<Contact.Status> status = new ComboBox<>("Status");
ComboBox<Company> company = new ComboBox<>("Company");
Button save = new Button("Save");
Button delete = new Button("Delete");
Button close = new Button("Cancel");
Binder<Contact> binder = new BeanValidationBinder<>(Contact.clreplaced);
private Contact contact;
public ContactForm(List<Company> companies) {
addClreplacedName("contact-form");
binder.bindInstanceFields(this);
status.sereplacedems(Contact.Status.values());
company.sereplacedems(companies);
company.sereplacedemLabelGenerator(Company::getName);
add(firstName, lastName, email, status, company, createButtonsLayout());
}
public void setContact(Contact contact) {
this.contact = contact;
binder.readBean(contact);
}
private Component createButtonsLayout() {
save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
delete.addThemeVariants(ButtonVariant.LUMO_ERROR);
close.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
save.addClickShortcut(Key.ENTER);
close.addClickShortcut(Key.ESCAPE);
save.addClickListener(click -> validateAndSave());
delete.addClickListener(click -> fireEvent(new DeleteEvent(this, contact)));
close.addClickListener(click -> fireEvent(new CloseEvent(this)));
binder.addStatusChangeListener(evt -> save.setEnabled(binder.isValid()));
return new HorizontalLayout(save, delete, close);
}
private void validateAndSave() {
try {
binder.writeBean(contact);
fireEvent(new SaveEvent(this, contact));
} catch (ValidationException e) {
e.printStackTrace();
}
}
// Events
public static abstract clreplaced ContactFormEvent extends ComponentEvent<ContactForm> {
private Contact contact;
protected ContactFormEvent(ContactForm source, Contact contact) {
super(source, false);
this.contact = contact;
}
public Contact getContact() {
return contact;
}
}
public static clreplaced SaveEvent extends ContactFormEvent {
SaveEvent(ContactForm source, Contact contact) {
super(source, contact);
}
}
public static clreplaced DeleteEvent extends ContactFormEvent {
DeleteEvent(ContactForm source, Contact contact) {
super(source, contact);
}
}
public static clreplaced CloseEvent extends ContactFormEvent {
CloseEvent(ContactForm source) {
super(source, null);
}
}
public <T extends ComponentEvent<?>> Registration addListener(Clreplaced<T> eventType, ComponentEventListener<T> listener) {
return getEventBus().addListener(eventType, listener);
}
}
16
Source : OrderEditor.java
with Apache License 2.0
from egetman
with Apache License 2.0
from egetman
@SuppressWarnings("FieldCanBeLocal")
clreplaced OrderEditor extends VerticalLayout {
private static final String PLACE_ORDER_URL = "http://localhost:8081/order/submit";
private transient Item sample;
private final transient RestTemplate restTemplate = new RestTemplate();
private final Text label = new Text("Place order");
private final TextField name = new TextField("Item name");
private final TextField quanreplacedy = new TextField("Item quanreplacedy");
private final Button order = new Button("Order", VaadinIcon.CART.create());
private final Button cancel = new Button("Cancel");
private final HorizontalLayout actions = new HorizontalLayout(order, cancel);
private final Binder<Item> binder = new Binder<>(Item.clreplaced);
OrderEditor(@Nonnull Runnable onRefresh) {
final HorizontalLayout input = new HorizontalLayout(name, quanreplacedy);
add(label, input, actions);
setSpacing(true);
setDefaultHorizontalComponentAlignment(Alignment.CENTER);
order.getElement().getThemeList().add("primary");
cancel.getElement().getThemeList().add("error");
order.addClickListener(e -> createCommand(sample, onRefresh));
cancel.addClickListener(e -> {
sample = null;
edireplacedem(null);
});
setVisible(false);
binder.forField(quanreplacedy).withConverter(new StringToLongConverter("Please enter a number")).bind(Item::getQuanreplacedy, Item::setQuanreplacedy);
binder.bindInstanceFields(this);
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));
restTemplate.setMessageConverters(Collections.singletonList(converter));
}
@SuppressWarnings("Duplicates")
private void createCommand(@Nonnull Item item, @Nonnull Runnable onRefresh) {
final PlaceOrder command = new PlaceOrder(item.getUuid(), item.getQuanreplacedy());
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
final HttpEnreplacedy<PlaceOrder> enreplacedy = new HttpEnreplacedy<>(command, headers);
try {
restTemplate.postForEnreplacedy(PLACE_ORDER_URL, enreplacedy, String.clreplaced);
onRefresh.run();
} catch (HttpClientErrorException e) {
final String errorMessage = e.getResponseBodyreplacedtring();
Notification.show(errorMessage, 3000, Notification.Position.MIDDLE);
}
setVisible(false);
}
void edireplacedem(@Nullable Item item) {
if (item == null) {
setVisible(false);
return;
}
setVisible(true);
sample = item;
binder.setBean(sample);
setVisible(true);
name.focus();
}
@Getter
@ToString
public static clreplaced PlaceOrder {
private final UUID itemUuid;
private final long quanreplacedy;
@ConstructorProperties({ "itemUuid", "quanreplacedy" })
PlaceOrder(UUID itemUuid, long quanreplacedy) {
this.itemUuid = itemUuid;
this.quanreplacedy = quanreplacedy;
}
}
}
16
Source : ItemEditor.java
with Apache License 2.0
from egetman
with Apache License 2.0
from egetman
@SuppressWarnings({ "FieldCanBeLocal", "WeakerAccess" })
public clreplaced ItemEditor extends VerticalLayout implements KeyNotifier {
private static final String CREATE_ITEM_URL = "http://localhost:8081/stock/create";
private transient Item sample;
private final transient RestTemplate restTemplate = new RestTemplate();
private final TextField name = new TextField("Item name");
private final TextField quanreplacedy = new TextField("Item quanreplacedy");
private final Button save = new Button("Save", VaadinIcon.CHECK.create());
private final Button cancel = new Button("Cancel");
private final HorizontalLayout actions = new HorizontalLayout(save, cancel);
private final Binder<Item> binder = new Binder<>(Item.clreplaced);
public ItemEditor(@Nonnull Runnable onRefresh) {
add(name, quanreplacedy, actions);
setSpacing(true);
setDefaultHorizontalComponentAlignment(Alignment.CENTER);
save.getElement().getThemeList().add("primary");
cancel.getElement().getThemeList().add("error");
addKeyPressListener(Key.ENTER, e -> createCommand(sample, onRefresh));
save.addClickListener(e -> createCommand(sample, onRefresh));
cancel.addClickListener(e -> {
sample = null;
edireplacedem(null);
});
setVisible(false);
binder.forField(quanreplacedy).withConverter(new StringToLongConverter("Please enter a number")).bind(Item::getQuanreplacedy, Item::setQuanreplacedy);
binder.bindInstanceFields(this);
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));
restTemplate.setMessageConverters(Collections.singletonList(converter));
}
@SuppressWarnings("Duplicates")
private void createCommand(@Nonnull Item item, @Nonnull Runnable onRefresh) {
final CreateCommand command = new CreateCommand(item.getName(), item.getQuanreplacedy());
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
final HttpEnreplacedy<CreateCommand> enreplacedy = new HttpEnreplacedy<>(command, headers);
try {
restTemplate.postForEnreplacedy(CREATE_ITEM_URL, enreplacedy, String.clreplaced);
onRefresh.run();
} catch (HttpClientErrorException e) {
final String errorMessage = e.getResponseBodyreplacedtring();
Notification.show(errorMessage, 3000, Notification.Position.MIDDLE);
}
setVisible(false);
}
void edireplacedem(@Nullable Item item) {
if (item == null) {
setVisible(false);
return;
}
setVisible(true);
sample = item;
binder.setBean(sample);
setVisible(true);
name.focus();
}
@Data
private static clreplaced CreateCommand {
private final String itemName;
private final long quanreplacedy;
@ConstructorProperties({ "itemName", "quanreplacedy" })
public CreateCommand(String itemName, long quanreplacedy) {
this.itemName = itemName;
this.quanreplacedy = quanreplacedy;
}
}
}
15
Source : CreateOrderView.java
with Apache License 2.0
from peholmst
with Apache License 2.0
from peholmst
@Route("create-order")
@Pagereplacedle("Create Order")
public clreplaced CreateOrderView extends VerticalLayout {
private final ProductCatalog productCatalog;
private final OrderCatalog orderCatalog;
private final Binder<OrderForm> binder;
private final Grid<OrderItemForm> itemGrid;
public CreateOrderView(ProductCatalog productCatalog, OrderCatalog orderCatalog) {
this.productCatalog = productCatalog;
this.orderCatalog = orderCatalog;
setSizeFull();
binder = new Binder<>();
var replacedle = new Html("<h3>Create Order</h3>");
add(replacedle);
var tabs = new Tabs();
tabs.setWidth("630px");
add(tabs);
var tabContainer = new TabContainer(tabs);
tabContainer.setWidth("630px");
tabContainer.setHeight("100%");
add(tabContainer);
var currency = new ComboBox<>("Currency", Currency.values());
binder.forField(currency).asRequired().bind(OrderForm::getCurrency, OrderForm::setCurrency);
tabContainer.addTab("Order Info", currency);
var billingAddress = new AddressLayout();
billingAddress.bind(binder, OrderForm::getBillingAddress);
tabContainer.addTab("Billing Address", billingAddress);
var shippingAddress = new AddressLayout();
shippingAddress.bind(binder, OrderForm::getShippingAddress);
tabContainer.addTab("Shipping Address", shippingAddress);
itemGrid = new Grid<>();
itemGrid.addColumn(form -> form.getProduct().name()).setHeader("Product");
itemGrid.addColumn(OrderItemForm::getQuanreplacedy).setHeader("Qty");
var orderItemLayout = new OrderItemLayout();
tabContainer.addTab("Items", new Div(itemGrid, orderItemLayout));
var createOrder = new Button("Create Order", evt -> createOrder());
createOrder.setEnabled(false);
createOrder.getElement().getThemeList().set("primary", true);
add(createOrder);
binder.setBean(new OrderForm());
binder.addValueChangeListener(evt -> createOrder.setEnabled(binder.isValid()));
tabs.setSelectedIndex(0);
}
private void addItem(OrderItemForm item) {
binder.getBean().gereplacedems().add(item);
itemGrid.sereplacedems(binder.getBean().gereplacedems());
}
private void createOrder() {
try {
var orderId = orderCatalog.createOrder(binder.getBean());
getUI().ifPresent(ui -> ui.navigate(OrderDetailsView.clreplaced, orderId.toUUID()));
} catch (Exception ex) {
Notification.show(ex.getMessage());
}
}
clreplaced AddressLayout extends VerticalLayout {
private TextField name;
private TextField addressLine1;
private TextField addressLine2;
private TextField postalCode;
private TextField city;
private ComboBox<Country> country;
AddressLayout() {
setPadding(false);
setWidth("630px");
name = createTextField("Name");
addressLine1 = createTextField("Address line 1");
addressLine2 = createTextField("Address line 2");
postalCode = createTextField("Postal code");
city = createTextField("City");
country = new ComboBox<>("Country", Country.values());
country.setWidth("100%");
var line1 = new HorizontalLayout(name, addressLine1, addressLine2);
line1.setWidth("100%");
var line2 = new HorizontalLayout(postalCode, city, country);
line2.setWidth("100%");
add(line1, line2);
}
private TextField createTextField(String caption) {
var field = new TextField(caption);
field.setWidth("100%");
return field;
}
private void bind(Binder<OrderForm> binder, ValueProvider<OrderForm, RecipientAddressForm> parentProvider) {
binder.forField(name).asRequired().bind(getter(parentProvider, RecipientAddressForm::getName), setter(parentProvider, RecipientAddressForm::setName));
binder.forField(addressLine1).asRequired().bind(getter(parentProvider, RecipientAddressForm::getAddressLine1), setter(parentProvider, RecipientAddressForm::setAddressLine1));
binder.forField(addressLine2).bind(getter(parentProvider, RecipientAddressForm::getAddressLine2), setter(parentProvider, RecipientAddressForm::setAddressLine2));
binder.forField(postalCode).asRequired().withConverter(new StringToPostalCodeConverter()).bind(getter(parentProvider, RecipientAddressForm::getPostalCode), setter(parentProvider, RecipientAddressForm::setPostalCode));
binder.forField(city).asRequired().withConverter(new StringToCityNameConverter()).bind(getter(parentProvider, RecipientAddressForm::getCity), setter(parentProvider, RecipientAddressForm::setCity));
binder.forField(country).asRequired().bind(getter(parentProvider, RecipientAddressForm::getCountry), setter(parentProvider, RecipientAddressForm::setCountry));
}
private <V> ValueProvider<OrderForm, V> getter(ValueProvider<OrderForm, RecipientAddressForm> parentProvider, ValueProvider<RecipientAddressForm, V> valueProvider) {
return orderForm -> valueProvider.apply(parentProvider.apply(orderForm));
}
private <V> Setter<OrderForm, V> setter(ValueProvider<OrderForm, RecipientAddressForm> parentProvider, Setter<RecipientAddressForm, V> setter) {
return (orderForm, value) -> setter.accept(parentProvider.apply(orderForm), value);
}
}
clreplaced OrderItemLayout extends HorizontalLayout {
private Binder<OrderItemForm> binder;
private ComboBox<Product> product;
private TextField quanreplacedy;
private TextField itemPrice;
private TextField tax;
private Button addItem;
OrderItemLayout() {
setWidth("630px");
setAlignItems(Alignment.END);
product = new ComboBox<>("Product", productCatalog.findAll());
product.sereplacedemLabelGenerator(Product::name);
add(product);
tax = new TextField("VAT");
tax.setReadOnly(true);
tax.setWidth("60px");
add(tax);
itemPrice = new TextField("Price");
itemPrice.setReadOnly(true);
itemPrice.setWidth("100%");
add(itemPrice);
quanreplacedy = new TextField("Qty");
quanreplacedy.setWidth("50px");
add(quanreplacedy);
addItem = new Button("Add", evt -> {
addItem(binder.getBean());
binder.setBean(new OrderItemForm());
addItem.setEnabled(false);
});
addItem.setEnabled(false);
add(addItem);
product.addValueChangeListener(evt -> {
var p = evt.getValue();
if (p == null) {
tax.setValue("");
itemPrice.setValue("");
} else {
tax.setValue(p.valueAddedTax().toString());
itemPrice.setValue(p.price().toString());
}
});
binder = new Binder<>();
binder.forField(product).asRequired().bind(OrderItemForm::getProduct, OrderItemForm::setProduct);
binder.forField(quanreplacedy).asRequired().withConverter(new StringToIntegerConverter("Please enter a valid quanreplacedy")).bind(OrderItemForm::getQuanreplacedy, OrderItemForm::setQuanreplacedy);
binder.addValueChangeListener(evt -> addItem.setEnabled(binder.isValid()));
binder.setBean(new OrderItemForm());
}
}
}