Localized error message for a Grails Validateable POGO's field
I often decorate my Grails Controllers with Traits. I often use is the following trait:
@CompileStatic
trait ValidateableMessageSource {
MessageSource messageSource
Optional<String> errorMessage(Validateable validateable,
String fieldName) throws NoSuchMessageException {
FieldError fieldError = validateable.errors?.getFieldError(fieldName)
if (!fieldError) {
return Optional.empty()
}
Optional.of(messageSource.getMessage(fieldError, LocaleContextHolder.locale))
}
}
I use a POGO to bind the HTTP Request body.
import grails.compiler.GrailsCompileStatic
import grails.validation.Validateable
@GrailsCompileStatic
class ContactSave implements Validateable {
String name
static constraints = {
name blank: false
}
}
This is how I use the trait in a controller:
class ContactController implements ValidateableMessageSource {
...
def save(ContactSave contactSave) {
if (contactSave.hasErrors()) {
String invalid = errorMessage(contactSave, "name").orElse(null)
ContactCreate contactCreate = new ContactCreate(name: contactSave.name,
nameInvalid: invalid)
render view: 'create', model: [contact: contactCreate]
return
}
String id = contactService.save(contactSave)
redirect(action: 'show', id: id)
}
}
Tags: #grails