如何将验证传播到 CustomField 子组件

Giu*_*nzo 3 vaadin vaadin-flow vaadin23

我有一个简单的 CustomComponent,其中 Person 是一个简单的数据类,有两个字符串 TextField:name 和 sname。

这是班级:

data class Person(var name:String, var birth:LocalDate)

class PersonField : CustomField<Person>(){

    private val nameField:TextField
    private val birthField:DatePicker

    init {
        nameField = TextField().apply {
            placeholder = "Name"

            addValueChangeListener{updateValue()}
        }

        birthField = DatePicker().apply {
            placeholder = "Birth"

            addValueChangeListener{updateValue()}
        }

        add(nameField, birthField)
        setWidthFull()
    }

    override fun setPresentationValue(person: Person?) {
        if (person != null) {
            nameField?.value = person.name
            birthField?.value = person.birth
        }
    }

    override fun generateModelValue(): Person {
        return Person(nameField.value, birthField.value)
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我使用两个验证器的活页夹:

binder.forField(personField)
            .withValidator({ value ->
                value?.name?.isNotEmpty() ?: false || value?.name?.isNotEmpty() ?: false
            }, "Name is Required")
            .withValidator({ value ->
                value.birth.isBefore(LocalDate.now())
            }, "Birth must be before today")
            .bind({person->person}, {person,field-> person.name=field.name;person.birth=field.birth})
Run Code Online (Sandbox Code Playgroud)

验证工作正常,但我想突出显示生成错误的特定字段。相反,它只给我错误消息:

在此输入图像描述

当正确的验证器触发时,如何使“名称”子字段变成红色?

Tat*_*und 6

您需要将活页夹移动到您的内部CustomField并绑定到内部TextField数据DateFieldDefaultValidator此外,当您这样做时,您可以在自定义字段内实现。就像是:

@Override
public Validator<LocalDate> getDefaultValidator() {
    return (value, context) -> { 
        if (binder.isValid()) {
            return ValidationResult.ok();
        } else {
            return ValidationResult.error("Person is not valid");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用另一个活页夹在表单中绑定 PersonField,这将链接内部和外部活页夹。