Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grails command object data binding of id field

When using command objects it seems I do not get automatic binding of the id field

class somethingCommand {

 int id
 String A
 String B

 // some methods here like Domain.get(id)

}

My A and B string get auto-magically data binded from the form properties but not id. The other "hidden fields" of grails like version, dateCreated or lastUpdated also get binded correctly.

My current patched solution is the following: I resort to defining another hidden id field in my form

<g:hiddenField name="blogId" value="${blog?.id}"/>

And rename id to blogId in the command obect and that works.

This does not seem to be in line with the elegance of Grails. What am I missing in the data binding rules of Command object vs controller?

like image 956
Stephane Rainville Avatar asked Jun 19 '11 00:06

Stephane Rainville


1 Answers

I have used this several times.

The id parameter is bound to your command as any other field. There is no special behaviour on this particular field

Now, if you are submitting a value for the id field that is incompatible with the type of your command's id field, then the field will not be bound. You will not get a ClassCastException or anything of the sort. You will just end up having a null value for the field.

I remember seeing something tricky about that: If you have an id in both your URL (ex. controller/action/id ) and in your form, then the id from the URL takes precedence.

So if your form has a proper hidden field for ID

<field type="hidden" name="id" value="1"/>

but the action is somehow screwed up on your form

<g:form action="doSometing" id="some-incompatible-value">...</g:form>

What you would receive in the controller is:

params.id = "some-incompatible-value"

Which would make it impossible for grails to convert your id parameter to a long or an int, and your command object would have

command.id = null

So, my advice would be : start over again and rewrite your form from scratch and make sure that the value in you form, as you see it from your controller's params.id is compatible with your command's id field type.

Let me know how it goes.

Vincent Giguère

like image 62
Vincent Giguère Avatar answered Oct 24 '22 01:10

Vincent Giguère