本系列文一開始有好幾篇文章都圍繞著CRUD轉,Vaadin 訂閱制提供了 CRUD component,今天要試試需要多少時間能寫完CRUD。資料使用 day23 下載的立委名單資料庫。
Vaadin 官方網站提供了 CRUD Component 詳細說明和範例程式,目前提供的版本為 21.0.3 (上週看還是21.0.2,Vaadin 版本更新速度算快),但本專案使用的是 Vaadin on Kotlin 框架,以 Vaadin 14 LTS 為基礎,故寫法和官網有點不太一樣。倘若您使用的是最新版本的 Vaadin,請參考官網範例。
如上所述,本專案使用 Vaadin 14.6.7(LTS) 版
vaadin_version=14.6.7
implementation("com.vaadin:vaadin-bom:${properties["vaadin_version"]}
implementation("com.vaadin:vaadin-crud-flow:${properties["vaadin_version"]}")
@Route("crud-legislator", layout = MainLayout::class)
@AllowAll
class LegislatorCrudView: KComposite() {
    private val root = ui {
        verticalLayout {
            setSizeFull()
            val grid = Grid(Legislator::class.java)
            val crud = Crud(Legislator::class.java, grid, createCrud())
            with(crud){
                setSizeFull()
                dataProvider = Legislator.dataLoader.asDataProvider()
                addSaveListener { it.item.save() }
                addDeleteListener { it.item.delete() }
                Crud.addEditColumn(grid)
                grid.removeColumnByKey("id")
                addThemeVariants(CrudVariant.NO_BORDER)
            }
            add(crud)
        }
    }
}
此畫面未設定哪些欄位要顯示,哪些不顯示,僅移除欄位 id,在此可使用addColumn限定欄位,如下所示 :
grid.addColumn(Legislator::name).setHeader("委員姓名")
grid.addColumn(Legislator::party).setHeader("黨籍")
綁定畫面和欄位使用 binder.bind(field, getter, setter),因Kotlin簡化setter/getter,為符合規格,使用Legislator::party.setter
fun createCrud(): CrudEditor<Legislator>{
    val txtName = TextField("委員姓名")
    val txtParty = TextField("黨籍")
    val formLayout = FormLayout(txtName, txtParty)
    val binder = Binder(Legislator::class.java)
    binder.bind(txtName, Legislator::name, Legislator::name.setter)
    binder.bind(txtParty, Legislator::party, Legislator::party.setter)
    return BinderCrudEditor(binder, formLayout)
}
為能使用.setter,須在gradle加上 :
implementation(kotlin("reflect"))
因版本用法差異,花了點時間debug,前後大約一個半小時左右。update 後立即同步到grid上,無須再執行任何更新。可以看到,程式碼非常的少,對於純文字的crud相當容易,相信加入 combobox、datepicker、...等components 應該也不是難事。pro component 確實大大減少開發時間。