First time working wtih checkboxes in Grails. What I want the checkbox to do is simply set a boolean variable to true if checked.
From the form.gsp:
<div class="form-group col-md-12 ${hasErrors(bean: apiInstance, field: 'oneWay', 'error')} ">
<label for="oneWay">
<g:message code="api.oneway.label" default="One Way" />
</label>
<g:checkBox name="oneWay " value="true" checked="${apiInstance?.oneWay == 'true'}"/>
</div>
In my domain class I have this defined:
Boolean oneWay = false
And in the service that is called from the controller I check the status of oneWay:
if (apiInstance.oneWay == true) {
log.info("One way flag is set.")
} else {
log.info("One way flag is not set.")
}
It's always false even when I check the checkbox. What act of stupidity am I committing? :D
I don't think you need to use the value and checked attributes, just use value like:
<g:checkBox name="oneWay " value="${apiInstance?.oneWay}" />
Related
I need to display 6 types of tests on my view and allow the user to check as many tests as they'd like to complete. I will then need to send their response to my controller so I can add that information to a database using the entity framework.
my View:
#using (Html.BeginForm("Quote", "Customers", FormMethod.Post))
{
<label for="test1"> BP</label>
#Html.CheckBox("test1", true)<br />
<label for="test2"> DS</label>
#Html.CheckBox("test2")<br />
<label for="test3"> IS</label>
#Html.CheckBox("test3")<br />
<label for="test4" class="iput">PS</label>
#Html.CheckBox("test4")<br />
<label for="test5">PF</label>
#Html.CheckBox("test5")<br />
<label for="test6">CS</label>
#Html.CheckBox("test6")<br />
<input type="submit" value="Begin Quote" class="btn btn-default" style="padding-left: 20px" />
}
and my controller method:
[HttpPost]
public ActionResult Quote(FormCollection collection )
{
if (!string.IsNullOrEmpty(collection["test1"]))
{
string checkResp = collection["test1"];
bool checkRespB = Convert.ToBoolean(checkResp);
}
return View("Index");
}
I am running into an issue when debugging...The collection["test1"] is returning a "true, false" value instead of the actual checked value of the checkbox. I cannot seem to get the form to collect the actual statuses of the check boxes.
I have tried other options but none have seemed to work. Any help is greatly appreciated!
I have a MVC View Model in which I have nullable boolean property:
[DisplayName("Is Active")]
public bool? IsActive { get; set; }
View:
<div class="col-md-3">
<div class="row">
<label>#Html.LabelFor(model => model.IsActive)</label>
</div>
#Html.RadioButtonFor(model => model.IsActive, true, new {id = "IsIsActiveTrue" })
<label>Yes</label>
#Html.RadioButtonFor(model => model.IsActive, false, new {id = "IsIsActiveFalse" })
<label>No</label>
#Html.RadioButtonFor(model => model.IsActive, "", new {id = "IsIsActiveAll"})
<label>All</label>
</div>
By default, I would like to select All when page loads. I tried to add
#checked = "checked"
but it didn't work (any of radiobutton value is selected). Please advise.
You cannot pass NULL as the value for the radio button when using RadioButtonFor helper method. If you pass ""as the value, you cannot set that in your GET action as your variable type is bool?,not string.
If you absolutely want 3 radiobuttons with your current type, you may simply write pure HTML code to render that. As long as your radio button's name attribute value matches your view model property name, model binding will work fine when you submit the form.
#using (Html.BeginForm("Search","Customer"))
{
<label>Active</label>
<input type="radio" name="IsActive" value="true"/>
<label>In Active</label>
<input type="radio" name="IsActive" value="false"/>
<label>All</label>
<input type="radio" name="IsActive" checked="checked" />
<input type="submit"/>
}
Here we are setting the checked attribute for all in the HTML markup.
Another option is to switch your controls from 3 radio buttons to 2 checkboxes. You can mark all of them checked initially and user may select/unselect as needed. Another option is changing your type from bool? to an enum with these 3 values. With both of these approaches, with the use of CheckBoxFor or RadioButtonFor helper, you should be able to set the items which needs to be checked, in your GET action method. Use the one which is more appropriate to your code structure/style.
I did it by replacing RadiobuttonFor with RadioButton:
<div class="row">
<label>#Html.LabelFor(model => model.IsActive)</label>
</div>
<div class="row col-md-12">
#Html.RadioButton("IsActive", true, false) Yes
#Html.RadioButton("IsActive", false, false) No
#Html.RadioButton("IsActive", null, true) All
</div>
In my view I have,
#Html.CheckBoxFor(m => m.IsExist, new { #id = "IsExist" })
In my Model I have IsExist value from DB. Either true or false.
Now how can I 'Check' or 'Uncheck' the option, based on the true or false value in IsExist.
I expected, on binding by default the check box takes the value of Model. Howeverr that is not happening.
How can i achieve it?
Here how i achieved it
#Html.CheckBox("VC",(item.isVC=="Y") ? true : false)
where my item.isVC has value "Y" or "N"
Below snippet indicates an alternate way of having checkbox created and conditionally making it checked/unchecked. The following approach is also useful to get the value of checkbox by traditional approach using jquery.
#model myproject.Models.StudentModel
<div class="row">
<label class="checkbox-inline">
<input type="checkbox" name="selfStudy" checked="#Model.IsExist"><b>Self Study</b>
</label>
</div>
You can do this to check a checkbox :
if (Model.IsExist) {
#Html.CheckBoxFor(m => m.IsExist, new { #id = "IsExist", "checked" = "checked"})
}
Hope it's help
Working with knockout.js (and knockout-validation) I have this:
self.nickname = ko.observable("").extend({
required: true,
minLength: 3
});
and
<input type="text" data-bind="value: nickname" class="short" maxlength="30" />
<div class="formRow rowErrorMsg" data-bind="visible: nickname.isValid() == false"><span class="staticImages staticImagesError"></span> <?php text("Enter a valid username") ?></div>
but the problem is that when "nickname" its not valid then apper a text next to the input control. The DIV with the error message start visible and then work fine.
I need to do this:
when "nickname" is not valid then just display the DIV with my custom message and format.
when page is loaded then the DIV have to stay hidden.
You need to configure knockout-validation to not show the error-messages. There are two ways.
The first is via binding:
<div data-bind='validationOptions: { insertMessages: false }'>
<input type="text" data-bind="value: nickname" class="short" maxlength="30" />
<div class="formRow rowErrorMsg" data-bind="visible: nickname.isValid() == false">
</div>
The second one is via code:
Use the ko.validation.init({ insertMessages: false }); function
Use the ko.applyBindingsWithValidation(viewModel, rootNode, { insertMessages: false }); function **contextual
A description of all configuration options can be found at: https://github.com/ericmbarnard/Knockout-Validation/wiki/Configuration
If you have many fields you have to validate you could use an messageTemplate template instead of manually creating all the errorMessage divs.
I've just met with a problem on how to use radio buttons. So this is my codes:
In GSP
<g:each in="${Query1}">
<label for="account_expired">Account Expired:</label><br />
<input type="radio" name="acc_expired" value="${it.acc_exp}" checked="checked"> True
<input type="radio" name="acc_expired" value="${it.acc_exp}"> False
<br />
</g:each>
In my controller:
if(params.username != null )
{
String updateQuery = "UPDATE sec_user SET account_locked='"+params.account_locked+"' WHERE Username='"+params.username+"'"
String queryname = "select * from sec_user where username = '"+params.username+"'"
def Query1 = sql.rows(queryname)
def update = sql.executeUpdate(updateQuery)
[update:update, Query1:Query1]
}
So, what I'm trying to do is how does the radio button check which values goes to which 'checked' radio button. Because I'm doing an edit page, so the controller will retrieve information from the database and auto select the radio button, whether is it 'True' or 'False'. In this case it's either '1' or '0'. So is there anyone out there can help me with this?
Thank you guys so much.
To have your view correctly check the radio you want, you need to add an expression to your tag. Also I suspect you don't want each button to have the same value. I'm guessing one should be true and the other false.
<input type="radio" name="acc_expired" value="${true}" ${it.acc_exp == true ? 'checked="checked"' : ''}> True
<input type="radio" name="acc_expired" value="${false}" ${it.acc_exp == false ? 'checked="checked"' : ''}> False
PS. You may want to look up SQL Injection.
will you explain it specifically ,However This may help you http://grails.org/doc/latest/ref/Tags/radioGroup.html
boolean[] acc_expired= [] //in your controller
and iterate this array to get their checked or unchecked index.