Vaadin服务端设置TextField值不触发CustomField::generateModelValue问题
问题根因
你的代码存在两处核心问题导致触发逻辑异常:
- 变量名拼写不一致,运行时会抛出空指针/未定义变量异常,打断
generateModelValue的执行链路 - 未给
Binder配置两个TextField和MyCustomPojo属性的对应绑定规则,Binder无法完成属性读写 - 代码调用
setValue方法默认生成的ValueChangeEvent标记为非用户触发,CustomField默认不会监听这类事件自动更新,不过你已经在handleSearchResult中手动调用了updateValue(),只要前面的语法错误修复就能正常触发。
修复步骤
- 统一所有成员变量名,删除不存在的
oriasModel判断逻辑 - 给两个TextField配置Binder绑定规则,指定对应的POJO属性
- 可选:如果需要代码设值时也触发和用户输入完全一致的事件链,可以在调用
setValue时追加第二个参数true标记为客户端触发事件
修正后代码示例
public class MyCustomField extends CustomField<MyCustomPojo> { private TextField freeTextField; private TextField searchTextField; private Binder<MyCustomPojo> binder; // 统一变量名,后续全用这个变量 private MyCustomPojo myCustomPojo; public MyCustomField(){ this.binder = new Binder<>(MyCustomPojo.class); this.myCustomPojo = new MyCustomPojo(); freeTextField = new TextField(); searchTextField = new TextField(); searchTextField.addFocusListener(event -> showSearchPopup()); // 新增绑定规则,替换成你实际POJO里的属性名和get/set方法 binder.forField(freeTextField) .bind(MyCustomPojo::getFreeContent, MyCustomPojo::setFreeContent); binder.forField(searchTextField) .bind(MyCustomPojo::getSearchResult, MyCustomPojo::setSearchResult); } public void handleSearchResult(String searchResult){ // 第二个参数true标记为用户端触发,可选,你已经手动调用updateValue可以不加 searchTextField.setValue(searchResult, true); this.updateValue(); } @Override protected MyCustomPojo generateModelValue() { binder.writeBeanIfValid(this.myCustomPojo); return this.myCustomPojo; } @Override protected void setPresentationValue(MyCustomPojo customPojo) { if(customPojo != null) { this.myCustomPojo = customPojo; binder.readBean(this.myCustomPojo); } } }
内容的提问来源于stack exchange,提问作者Ronan Quintin
相关产品推荐
相关产品推荐

