eu.vaadinonkotlin.vaadin8.vokdb.Converters.kt Maven / Gradle / Ivy
package eu.vaadinonkotlin.vaadin8.vokdb
import com.github.vokorm.KEntity
import com.gitlab.mvysny.jdbiorm.Dao
import com.vaadin.data.Binder
import com.vaadin.data.Converter
import com.vaadin.data.Result
import com.vaadin.data.ValueContext
/**
* Converts an entity to its ID and back. Useful for combo boxes which shows a list of entities as their options while being bound to a
* field containing ID of that entity.
* @param T the type of the entity
* @param ID the type of the ID field of the entity
*/
public class EntityToIdConverter>(public val dao: Dao) : Converter {
public constructor(clazz: Class) : this(Dao(clazz))
override fun convertToModel(value: T?, context: ValueContext?): Result =
Result.ok(value?.id)
override fun convertToPresentation(value: ID?, context: ValueContext?): T? {
if (value == null) return null
return dao.findById(value)
}
}
/**
* Converts an entity to its ID and back. Useful for combo boxes which shows a list of entities as their options while being bound to a
* field containing ID of that entity:
* ```kotlin
* data class Category(override var id: Long? = null, var name: String = "") : Entity
* data class Review(override var id: Long? = null, var category: Long? = null) : Entity
*
* // editing the Review, we want the user to be able to choose the Review's category
* val binder = BeanValidationBinder(Review::class.java)
* val categoryBox = comboBox("Choose a category") {
* setItemCaptionGenerator { it.name }
* isTextInputAllowed = false
* dataProvider = Category.dataProvider
* bind(binder).toId().bind(Review::category)
* }
* ```
*/
public inline fun > Binder.BindingBuilder.toId(): Binder.BindingBuilder =
withConverter(EntityToIdConverter(ENTITY::class.java))
© 2015 - 2025 Weber Informatics LLC | Privacy Policy