Tuesday, November 25, 2008

Adding your own error message to a Grails Command Object

Here is another little trick I got to use in Grails recently:

Before I started using Grails I used Spring MVC and in fact i still do i my day job. Any way one of the things Spring provided was the Errors interface. This allowed you to add your own error message that would end up available to your view layer. By using methods such as

reject() and rejectValue()

So as Grails is built on top of Spring it also makes use of the Errors interface and it automatically injects an instance of this into your domain objects and command objects.

So in your controller if you want add an error message to your command object (eg HolidayQueryCommand)

Then all you have to is this:

holidayQueryCommand.errors.reject("message.code","default error message");

If you wanted to attach and error message to a particular property then do this:

holidayQueryCommand.errors.rejectValue("property","message.code","default error message");

These error messages are then all available in your GSP:

<g:rendererrors bean="${holidayQueryCommand}" as="list"></g:rendererrors>

That also goes for domain objects too not just command objects.

If this is useful to even 1 person then i am glad i posted it :)

16 comments:

Martin Flower said...

I was puzzling about this for a while. So, yes, it is helpful to me, and yes, thank you for posting it. Cheers. Martin.

Anonymous said...

Thanks Man

ed said...

Nice! Worked as specified.

Inam said...

Great work, Thanks

Tim said...

This sort of works for me except I cannot pick up the message from the messages.properties. It always displays the default message. Anyone got this working?

Cheers, Tim

Anonymous said...

Thanks you saved my day

IRGeek said...

Just what I needed. thx. It properly pulls from message.properties for me. Make sure message.properties already getting used properly for a validating a domain object or similar first. If that works, should also work when u set the error. good luck.

DreamerForever said...

it works, but i also get the default error messages out there. So I get double error messages printed out. please help.

Sumit said...

Thanks, this helped!

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

Binni said...

This is really helpful friend.
Thanks a lot.

Anonymous said...

One more guy who wondered about this and was helped!

Cheers,
Hakan

Anonymous said...

Thanks for the help

dhpye said...

Thanks a tonne for this. I'd been struggling for a couple of hours with what seemed like trivial custom validation, this pulled it all together with one line of code.

MR. B said...

Very nice. Thanks

Chris Bartling said...

Very helpful. Thanks!!