Bind property of optional subtype

Hi there, I’m sure there is a nicer way to do that:

binder.forField(firstname)
        .asRequired("Firstname is mandatory")
        .bind(new ValueProvider<MoUFormular, String>() {
			
			@Override
			public String apply(MoUFormular source) {
				return source.getPerson().map( Person::getFirstName).orElse("");
			}
		}, new Setter<MoUFormular, String>() {
			
			@Override
			public void accept(MoUFormular bean, String fieldvalue) {
				bean.getPerson().ifPresent(person -> person.setFirstName(fieldvalue));				
			}
		});

But i didn’t find any solution. I’m using vaadin 14

Thanks !

P.S. or do i have to use 2 binders ?

No that looks good. It only is this ‘ugly’ because you need to not only check for optional, but also the firstName is not a direct property of NoUFormular. The only way I see to make this code nicer is to use lambda for getter and setter:

binder.forField(firstName)
	.asRequired("Firstname is mandatory")
	.bind(
		(moUFormular) -> moUFormular.getPerson().map(Person::getFirstName).orElse(""),
		(moUFormular, value) -> moUFormular.getPerson().ifPresent(person -> person.setFirstName(value))
	);

Note that this is only syntactical sugar and I have changed nothing in the logic of your code. My code and yours are “the same”, if only looking different. Personally I would recommend using lambda wherever possible, developing with Vaadin will provide many opportunities for using lambda. It just looks and reads so much better IMO.