grailsgrails-filters

flash.message in grails filter


in my Grails application , i made a filter on a controller , all working fine except this part :

flash.message = message(code: 'empSeeker.profileExists')

and the error is :

Message:No signature of method: com.MyApp.filters.HRCheckFilters.message() is applicable for argument types: (java.util.LinkedHashMap) values: [[code:empSeeker.profileExists]] Possible solutions: isCase(java.lang.Object)

but if i changed it with flash.message="Any message" it works,

Any reason why it is not working ?


Solution

  • I thought that most things like this that work in a controller also work in filters, but apparently not. In this case there's a workaround that's actually a better approach.

    message works in a controller because controllers support calling taglibs directly, and if the namespace is g then you can omit it, so calling message or g.message in a controller both invoke the <g:message> taglib. But all the taglib does is render messages from the messageSource Spring bean, so you can skip a layer or two of indirection and call that directly.

    Add this import to your filters class

    import org.springframework.context.i18n.LocaleContextHolder
    

    and this dependency injection

    def messageSource
    

    and then you can set the flash message with

    flash.message = messageSource.getMessage('empSeeker.profileExists',
                                              null, LocaleContextHolder.locale)