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

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>

Related

how to set radio button for edit in 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>

OptionValue in Grails Select with list of domain objects

I've done some research on how to display a dropdown with an optional value. Currently, I have a list of domain objects (people) in a dropdown. They display with "First name last name".
I want to change the way the names are displayed in a selection. Looking at the g:select API, I see I can use optionValue and optionKey. I've tried, but got nowhere. So here is my current code:
<g:select id="allPeople" name="allPeople" from="${dropdown}" />
I want the output to be "Last, First". I've tried this:
<g:select id="allPeople" optionValue="${it?.last},${it?.first}" from="${dropdown}" name="allPeople" value="" >
A nice way to do it is to add a transient getter on your domain, then use that for the optionValue.
class Person {
String first
String last
static transients = ['lastFirst']
String getLastFirst() {
"$last, $first"
}
}
then
<g:select name="allPeople" optionValue="${it.lastFirst}" from="${dropdown}"/>
Try like this:
optionValue="${{it?.last+', '+it.first}}"
This mean that you pass a closure that builds what you need.

<g:countrySelect> Tag: How to set values as country names instead of country codes

On my view, instead of using a normal <g:textField> field in the form, I would like to make use of Grails' <g:countrySelect> widget.
My problem
<g:countrySelect name="country" value="${myObjInstance?.country}"/>
...produces...
<select name="country" id="country">
<option value="afg">Afghanistan</option>
<option value="alb">Albania</option>
...
</select>
This would mean that, when the form is submitted, it will assign the value as country code (e.g. "afg") instead of the country name ("Afghanistan"). I prefer using the full country name as value. If possible, how do I achieve this?
I don't believe the taglib as is gives you that ability. You would either need to extend it or use your own Country collection + <g:select />
Another option would be to use this enum of the ISO_3166 country codes to get the full length description. Eg:
CountryCode.getByCode(params.country).getName()
To answer my own question...
The values can stay as is (country codes) and then just use country codes. On your views, you can make use of the grails country() method to display the country name, e.g.
Let's say the country code is "afg" (the value saved in your table). On your view (GSP) you can use
<div>${country(code: fieldValue(bean: myObjInstance, field: "country"))}</div>
This will print out
<div>Afghanistan</div>
Instead of
<div>${fieldValue(bean: myObjInstance, field: "country")}</div>
...that was used before:
<div>afg</div>

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.

asp.net MVC checkbox headache!

I have seen lots of questions relating to this topic.
I am using asp.net MVC 1.0
Problem area
If I use
<%= Html.CheckBox("Status", true) %>
Then why It renders like
<input checked="checked" id="Status" name="Status" type="checkbox" value="true" /><input name="Status" type="hidden" value="false" />
I put this in foreach loop and I have 5 rows.
when I submit form with true,true,true,false,false
then I get true,false,true,false,true,false,false,false
i.e. for false => false.
for true => true,false
If I use
<input type="checkbox" value="true" name="Status" checked="checked" />
Then I don't get unchecked one's.
so how do I overcome form this problem?
Please don't post answer with using loop in formcollection object and checking each key!
I know this isn't the elegant one but this is what I did:
collection["response"].Replace("true,false", "true").Split(',').ToList();
In your example, when you submit form with true,true,true,false,false and you get
true,false,true,false,true,false,false,falseit is interesting to note that you are not actually getting eight values back, but five arrays that merely looks like this is the case because all of the values are joined.
I know you asked to not get a loop for your answer, but I can use one to demonstrate what is really happening here:
foreach (string key in postedForm.AllKeys) {
// "value" will contain a joined/comma-separated list of ALL values,
// including something like "true,false" for a checked checkbox.
string value = postedForm[key].GetValue;
// "values" will be an array, where you can access its first element,
// e.g., values[0], to get the actual intended value.
string[] values = postedForm.GetValues(key);
}
So, for your checked boxes, you'll get a values array with two elements, and for unchecked boxes, you'll get just a single-element array.
Thus, to answer your question how do you overcome this problem, the answer lies in using GetValues rather than GetValue, and thinking of your posted fields as arrays rather than strings.
Best of luck!
Personally I think having to check for "true,false" everywhere on the server is a pain. I wrote a jquery fix that will remove the extra hidden field created by the Html.Checkbox helper when a box is checked, then add it back if the box is unchecked. Server values will always be "true" or "false". Checkbox lists are kind of subjective in how you want them to act, which I discuss, but I'm removing "false" from the value set, which means the form value will be excluded if all boxes in the list are unchecked.
http://www.mindstorminteractive.com/blog/?p=386
I've had pretty good success using this technique. Please let me know if you try it out and have issues.
You'll have to do your own model binding for the CheckBox values.
Get the list of values from the FormCollection or Request.Form for that CheckBox id and replace true,false with true:
string chkBoxString = Request.Form["checkboxID"].Replace("true,false", "true")
Now you have a list of whether a CheckBox was selected or not.... do the rest yourself :)
It renders so because default binder requires the FormCollection to have a value for nonnullable parameters. Using this technique we are sure that the value will be sent even the checkbox is not checked (by default the value sent only when it's checked). If you use this controller method with just one html input you'll get error on form post with unchecked checkbox (value of checkbox will not be posted and binder will not know what to use for value of isItemSelected):
public ActionResult SomeActionMethod(bool isItemSelected)
You can try use something like this with just one html input:
public ActionResult SomeActionMethod(bool? isItemSelected)
But in this case isItemSelected will be null or will be true. And it will never become false.
Well there are couple of ways you can do based on your requirement.
I use this method.
<input type="checkbox" value="<%= item.ID %>" name="check" checked="checked")" />
This is may checkboxes.
On server side I will also have array of ID's of item in the model.
So I check it whether it is in array
var strArray = form["checkbox"]; //Request.form["checkbox"] or "FormCollection form" in action parameter; array of ID's in comma separated string.
Different people have different tests.
this was intended to use for just just simple CheckBox, what you want is checkboxList, which is not yet cover in the API of ASP.net MVC
If you looking for some thing like checkboxlist, maybe you should write your own helper, provide you understand HTML well..
That's it! :)
Easier just to check whether AttemptedValue.Contains("true") - it will, if it's checked, not if it's unchecked....
in the View :
<input id="radio5" type="checkbox" name="rb_abc" value="5"/>
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult YourForm(FormCollection fc)
{
if (fc["rb_abc"] == "on")
{
//Hey .. you have selected a Radio Button.. just kidding.. its a CheckBox
}
}
To get checkbox value even it is true or false
var boolValue = bool.Parse(collection.GetValues("checkboxID")[0])

Resources