how to set radio button for edit in grails - grails

I am using grails 2.1.1 I have a domain where I want to save religion of member. I am saving it there is no problem. But when I go to edit page then it does not checked the original value.Suppose I am saving a religion for Buddhist and at the time of edit I want to be checked the value of it. But it is checking for Muslim. I want the field to be checked on edit page. Can anyone please help me on this please ??!!! Here are my attempts below ::
my domain class >>>
class RadioButton {
String religion
static constraints = {
}
}
my form page >>>
<div class="fieldcontain ${hasErrors(bean: radioButtonInstance, field: 'religion', 'error')} ">
<label for="religion">
<g:message code="radioButton.religion.label" default="Religion"/>
</label>
<g:radio name="religion" value="muslim" checked="checked"/> Muslim <br/>
<g:radio name="religion" value="hindu"/> Hindu<br/>
<g:radio name="religion" value="christian"/> Christian<br/>
<g:radio name="religion" value="buddhist"/> Buddhist
</div>

You may want to consider the radioGroup tag within Grails instead of manually authoring your radio buttons.
However, if you decide to continue manually authoring your radio buttons you will need to account for selecting the current value. For example:
<g:radio name="religion" value="muslim" checked="${radioButtonInstance?.religion.equals('muslim')}"/>
In the above example you will notice that the checked attribute is being set to a boolean value (which is correct according to the documentation).

I think radioGroup is by far a better solution for you as you are using grails.
They main problem is that you are not passing the currently set religion to the GSP. There is nothing telling the radio group which religion has already been set by the user, instead Muslim has been hard-coded with the checked="checked".
Judging from your first line which sets the class of the div if the bean has an error, I assume you can access the currently set religion from the radioButtonInstance. Using the radioGroup tag you pass the currently set value as ${radioButtonInstance?.religion}, then we set the values and the labels you need, as shown:
<g:radioGroup name="religion"
values="['Muslim', 'Hindu', 'Christian', 'Buddhist']"
labels="['Muslim', 'Hindu', 'Christian', 'Buddhist']"
value="${radioButtonInstance?.religion}">
<p>${it.label}: ${it.radio}</p>
</g:radioGroup>
I would, however, suggest that you set the available religions as an enum class rather than hard coding it onto the GSP, as you might want to reuse it. You could then pass it as a variable in the model through the controller, calling it, for example, religions, then your radioGroup would look like:
<g:radioGroup name="religion"
values="${religions}"
labels="${religions}"
value="${radioButtonInstance?.religion}">
<p>${it.label}: ${it.radio}</p>
</g:radioGroup>

Related

grails .gsp - how do I embed object properties when saving with a parent object

I have a report page where the user is able to enter a number of totals. Each of these totals is a domain object in it's own right and has a number of properties of it's own that need to be persisted. For each of the totals, the user can only enter data into one field, which is just a number, yet the other properties of the total object are determined by where the particular total is output in the page.
I'd like to be able to save the whole report, and each on of those totals from just the one page.
What I can't work out is how do I add the extra params to each of the domain objects at the gsp end.
Say I have the following where ${reportInstance} is the report that I'm currently working with but ${reportInstance?.totalHours? refers to one of many totalHours objects I need to save from this page.
<input type="number" size="6" min="0" class="count-${location}" name="count-${location}" value="${reportInstance?.totalHours?.total}">
This input field gives me it's 'total' but I also need to save other properties for it such as ${location} as well as others...
How do I add the extra properties to the single form value so that the controller can pick it up?
EDIT:
Am I able to nest properties in the value by doing something like:
<input type="number" size="6" min="0" class="count-${location}" name="count-${location}" value="${reportInstance?.totalHours?.total(location:location)}">
??
I think that what you're looking for is:
<g:hiddenField name="myField" value="myValue" />

How to bind list of dynamic objects to the Model

I have a strongly typed view where one of the properties of the model that is passed in is a list of objects. I am handling dynamic binding of inputs to this list by using the BeginCollectionItem helper which works fine. However, I also want to initially have a group of inputs visible on the view that will bind to the 'first' object in the list.
I've tried just copying the inputs that BeginCollectionItem generates but that doesn't seem to work.
It generates inputs with name attributes like
invoiceItems[ef43a8f2-c6b7-4791-bf7f-6764c8e3fc9b].Description
invoiceItems[ef43a8f2-c6b7-4791-bf7f-6764c8e3fc9b].Cost
so I manually put 2 inputs on the view with the name attributes
invoiceItems[firstOne].Description
invoiceItems[firstOne].Cost
but it didn't show up in the model on the controller after submitting the form.
I can't just insert one the BeginCollectionItem way when the view loads because the initial item has to be displayed differently.
Not exactly answer to your question, but I hope it will solve your problem.
Instead of changing the name in the view, you may try changing the model. Add a boolean property IsFirst. I believe you know in the controller(or wherever the model is being instantiated) which one is first. Set the first items IsFirst to true.
I figured it out. I was on the right track with manually putting in the stuff that BeginCollectionItem did, I was just missing a part. You need another hidden input that tells the binding what the index you're using is.
So the following works perfectly
<input type="hidden" name="invoiceItems.index" autocomplete="off" value="firstOne" />
<input type="text" placeholder = "ex. Labour" id="invoiceItems_firstOne__Description" name="invoiceItems[firstOne].Description" />
<input type="text" placeholder = "ex. $15" id="invoiceItems_firstOne__Cost" name="invoiceItems[firstOne].Cost" />
I just added the top hidden input to what I had before and it's all good.

Grails setting values in Select (dropdown menu) for a boolean

I'm using the Grails framework. In my User controller, I have a boolean field named "active" which controls if users are allowed to login. The login action checks this value when the user is logging in.
My domain:
class User {
Boolean active
}
My view (edit.gsp):
<g:select id="active" name="active" from="${[1,0]}" value="${userInstance?.active}" />
The value saves correctly into the database, but I want the Account Status dropdown to say "Enabled" or "Disabled", instead of "1" or "0" as it does now.
It also should show the current value when the Edit page is loaded. Currently, it always shows the value of "1", even if the user has the value of "0" in the database.
This seems like it would be very easy, but I haven't been able to find any examples of anyone setting their dropdown values in the GSP, and nothing I've tried so far is working. Thanks!
I see two solutions, both in the documentation.
One is to us the keys parameter of the tag:
<g:select id="active" name="active" from="${['Enabled','Disabled']}" keys="${[1,0]}" value="${userInstance?.active}" />
This provides a different list of keys vs the list of values.
The other solution is to use the optionKey and/or optionValue parameters, but this is would would require the list to contain objects or something similar that could be used to look up the values:
In src/groovy/BooleanSelectOption.groovy:
class BooleanSelectOption {
String name
String value
private BooleanSelectOption(name, value) {
this.name = name
this.value = value
}
private static List _list;
public static List getList() {
if(!BooleanSelectOption._list) {
BooleanSelectOption._list = [new BooleanSelectOption('Enabled',1), new BooleanSelectOption('Disabled',2)]
}
BooleanSelectOption._list
}
public String toString() { name }
}
In your view:
<g:select id="active" name="active" from="${BooleanSelectOption.list}" optionKey="value" value="${userInstance?.active}" />
Now the tag is looking up the key based on a bean property of the items in the list. Also, an enum might work here, too.
Obviously the first technique is cleaner for short lists, but I wanted to show both options for more complex situations. I haven't tested the second example, either.
One more note: You will probably find that the keys 0 and 1 don't really work, because Disabled will not get selected (in my experience) if the value is false. I don't know if you can get away with using true and false, but you should test to make sure you are getting what you expect.
There's actually a third option, probably the most robust solution, also in the docs:
Use the valueMessagePrefix parameter to allow the displayed value to be looked up from the i18n messages.
In grails-app/i18n/messages.groovy:
boolean.select.0=Disabled
boolean.select.1=Enabled
In your view:
<g:select id="active" name="active" from="${[1,0]}" value="${userInstance?.active}" valueMessagePrefix="boolean.select" />
This has the additional benefit of allowing you to have different labels for different languages, if you ever need it.
You can use optionKey and optionValue to use an object property or map value for the keys and values. Try something like this:
<g:select name="active" optionKey="key" optionValue="value"
from="${[[key: 1, value: 'Enabled'],[key: 0, value: 'Disabled']]}"/>
Just as an alternative for cases like this when there appears there will be much more processing involved than the task warrants remember you can just fallback to plain old html. E.g.
<select name="active">
<option value="0" ${!active ? 'selected' : ''}>Disabled</option>
<option value="1" ${active ? 'selected' : ''}>Enabled</option>
</select>

GSP- Select tag. How to achive selected="selected"

I have a select tag in my GSP file as
<g:select name="clientId" id="clientId" size = "4" from="${com.springcommunity.fleet.partymodel.roles.ClientRole.list()}" class = "filter_combo" optionKey="id" />
i want client with id 2 is selected initially (in simple html it is achived by using selected="selected")
how can i do it?
You need to specify the value attribute in this tag. http://grails.org/doc/2.0.x/ref/Tags/select.html
So in your example,
<g:select ... value="${com.springcommunity.fleet.partymodel.roles.ClientRole.get(2)}" />
One thing to be aware of here is that the value that you're selecting must be an object equal to the item in the list, and not just an id - this is where a lot of people get tripped up. So you can't just say value='2', you need to specify the object in the list that you have in your from attribute.
From the docs -
value (optional) - The current selected value that evaluates equals()
to true for one of the elements in the from list.

How to mimic MVC's checkbox -> bool model binding?

I've got an editor template which renders out a checkbox:
#Html.CheckBoxFor(model => model.Follow)
Which renders something like this:
<input checked="checked" data-val="true" data-val-required="The Follow field is required." id="Follow" name="Follow" type="checkbox" value="true" />
<input name="Follow" type="hidden" value="false" />
AFAIK the hidden field is something to do with catering when an unchecked box isn't sent to the server or something.
Anyway, if i take a look at the Request.Form["Follow"] when the checkbox is checked, i see a value of "true,false".
How do i coerce a bool from this value? Do i simply ignore the second field? (e.g the hidden field).
I'm doing this is a base controller (protected method, invoked from child controller), so i don't have a strongly-typed view model, only the raw Request object.
Can anyone help? Or alternatively, if someone could point me to where in the MVC source code this happens, i could take a look myself, but not sure where to start looking.
You are correct the hidden field is just so the form will be submitted to the server. Because if the form had just checkboxes that are not checked then nothing will be submitted and the server would not know to set them to false.
You only require 1 hidden field per form, you do not need one per checkbox. But if your making your own control it is hard to tell if a hidden textbox is already on the field or not. If you know you are always going to have a textbox or select list etc somewhere else on your forms you do not need a hidden textbox at all
You can rename your hidden textbox to anything name it "dummy" or something different to the checkbox name so Request.Form["Follow"]; will only return the value of the check box not need to split. You never need to check the value of the "hidden textbox".
On a side note you shouldn't be using Request.Form["Follow"] you Action method should have a parameter like this instead "bool? follow"
MVC helper renders checkbox input control with two input fields, the checkbox and the hidden, because the browser do not send a value for checkbox input field if the checkbox is not selected. If you do not use auto mapping, you need to parse the input value that you receve from your form.
Use this simple rule to detect the checkbox:
var rawFollow = Request.Form["Follow"];
if (rawFollow.Contains("true"))
{
// do something
}
As far as i know, the extra hidden field is because if the checkbox is NOT checked, that input will not be submitted with the form and therefore we need the hidden field with the value of false.
So the only solution is can think of is this:
var rawFollow = Request.Form["Follow"];
var rawFollows = rawFollow.Split(',');
if (rawFollows.Count() > 1)
{
rawFollow = rawFollows[0];
}
But this seems hacky (and what about the order of the elements on the page, what if for some reason the hidden field was FIRST, then it would always evaluate to false), which is why i'm wondering how the MVC source does this.

Resources