Grails - g:field reset and html reset won't clear form/params/session - grails

Using Grails 3.0.9
Making a Clear Form/session button for the filter class. however nothing i do works.
The button is just stuck there, nothing happens
Any help will be appreciated
SupplyController
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
if (params.name)
session.name = params.name
else if (request.method != "POST")
params.name = session.name
else
session.name = null
def criteria = Supply.createCriteria()
def query = {
and{
if (params.name) {
like ("name", '%' + params.name + '%')
}
}
}
def results = criteria.list(params, query)
respond results, model:[supplyCount: results.getTotalCount()]
}
G:field type of code
<div class="filter">
<h3>Filter:</h3>
<g:form action="index" method="post" >
<label for='name'>Name:</label>
<input type="text" id="name" name="name" value="${session.name}"/><br/>
<span class="button">
<g:submitButton name="index" class="index" value="Apply Filter" /></span>
<g:field type="reset" name="myReset" value="Reset" />
</g:form>
</div>
HTML tag type
<div class="filter">
<h3>Filter:</h3>
<g:form action="index" method="post" >
<label for='name'>Name:</label>
<input type="text" id="name" name="name" value="${session.name}"/><br/>
<span class="button">
<g:submitButton name="index" class="index" value="Apply Filter" /></span>
<input type='reset' value='Reset' />
</g:form>
</div>

An HTML form reset button for a form rests the form to the initial state. In this case back to the values it had when the form loaded. A HTML form reset button does not CLEAR the form or CLEAR the session.

wondering why you are using session for where typicalls form params should be used? In order to clear HTML session you would need to trigger a call back to the originating controller just like you would to post but when it receives via this call. It does a session.invalidate() and then renders same view again. You should try to stick with params for forms. The fact that you have the session information already really no need to post it via a form. Your controller receiving the form would be aware of that same session value.
You could easily create a jquery functionality that you do with a button that triggers and a resetform. jQuery/Javascript function to clear all the fields of a form
Or if that does not work you could try for example in your case:
<g:form ..>
..
<button onClick="clearName();" name="clickme">
</g:form>
<g:javascript>
function clearName() {
$('#name').val();
}
</g:javascript>

Related

Grails - error 404 on form submit using g:actionSubmit

I'm new on Grails and I'm having trouble to do a form submit.
Here is AnimaisController:
package jogoanimais
class AnimaisController {
def index() {
def animalsTreeObj = AnimaisTreeMap.list()
render(view: "show", model: [animalList: animalsTreeObj])
}
def addNode()
{
log.info "add node"
log.info params
}
}
Here is show.gsp
<g:form controller="animais" action="addNode">
<div>Pense em um animal</div>
<g:textField name="myField" value="${myValue}" />
<g:actionSubmit value="OK, próximo" />
<g:each in="${animalList}" var="row" status="i">
<h3> ${row.nodeDescription}, ${row.yesAnswerNode}</h3>
<br/>
</g:each>
</g:form>
After clicking at the submit button, the URL that is requested is "http://localhost:8080/jogoAnimais/animais/addNode" and I get a 404 error.
I've also tried adding "action" do g:actionSubmit but in this case, Grails requested a addNode.gsp.
Does anyone has any idea?
Here's the solution:
GSP:
Add "action" parameter of g:form and a input type "submit" as shown below:
<g:form controller="animais" action="addNode">
<div>Pense em um animal</div>
<div>
<label for="questionToUser">Questão:</label>
<g:textField name="questionToUser" maxlength="50"/>
</div>
<input type="submit" value="Submit">
<g:each in="${animalList}" var="row" status="i">
<h3> ${row.nodeDescription}, ${row.yesAnswerNode}</h3>
<br/>
</g:each>
</g:form>
CONTROLLER:
As mbaird has said, my "addNode" mehtod need to return something, as "render 'ok'"

Browser Rember me Password prompt disable

I want to disable the remember me password prompt of IE/firefox/chrome browser
may developer and blog suggest me to add autocomplete ="off" in <form> tag
but it's not working.
Please give suitable answer thank in advance..
//You can change the type of the password field to text before submitting the form
<script type="text/javascript">
function validate() {
return true;
}
function copyPass() {
document.getElementById("hidPassword").value = document.getElementById("passwordField").value;
if (document.getElementById("passwordField").value != "") {
var passwordLength = document.getElementById("passwordField").value.length;
document.getElementById("passwordField").value = "•".repeat(passwordLength);
}
document.getElementById("passwordField").type = 'text';
}
function changeType() {
document.getElementById("passwordField").type = 'password';
document.getElementById("passwordField").value = document.getElementById("hidPassword").value;
}
</script>
<form method="post" action="yoururl" runat="server">
<input type="text" name="username" />
<input type="password" id="passwordField" name="passwordField" onfocus="javascript:changeType()" onblur="javascript: copyPass()" />
<input type="hidden" name="hidPassword" id="hidPassword" value="" />
<input type="submit" runat="server" name="btnsubmit" value="Submit" onclick="javascript:return validate()" />
</form>
Instead of setting autocomplete="off" on a <form> tag, set it on the individual <input> tags.
For browser support, see caniuse.

Checking & Unchecking Checkboxes inside a JQuery Mobile Dialog

I tried this code to achieve what I want to do. It worked when I tried it in my ordinary HTML file, but when I tried it in my JQuery Mobile page, the code did not work well for me. Are there different ways or code to select JQuery Mobile checkboxes?
Here's the code that I tried:
JAVASCRIPT:
<script>
function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
if(!document.forms[FormName])
return;
var objCheckBoxes = document.forms[FormName].elements[FieldName];
if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;
if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
objCheckBoxes[i].checked = CheckValue;
}
HTML
<form method="GET" name="myForm" onsubmit="return false;">
<label for="myCheckbox1">
<input type="checkbox" name="myCheckbox" value="1" id="myCheckbox1">
I like Britney Spears
</label>
<br>
<label for="myCheckbox2"><input type="checkbox" name="myCheckbox" value="2" id="myCheckbox2">
I like Hillary Duff
</label>
<br>
<label for="myCheckbox3"><input type="checkbox" name="myCheckbox" value="3" id="myCheckbox3">
I like Mandy Moore
</label>
<br>
<input type="button" onclick="SetAllCheckBoxes('myForm', 'myCheckbox', true);" value="I like them all!">
<input type="button" onclick="SetAllCheckBoxes('myForm', 'myCheckbox', false);" value="I don't like any of them!">
I was not aware that JQuery Mobile's checkboxes need to be refreshed after unchecking/checking them via JQuery or Javascript. Here's the code:
$("input[type='checkbox']").attr("checked",true).checkboxradio("refresh");
http://api.jquerymobile.com/checkboxradio/#method-refresh
Try this:
function SetAllCheckBoxes(FormName, CheckValue){
$.each($("#"+FormName+" input[type=checkbox]"), function(){
$(this).attr("checked",CheckValue).checkboxradio("refresh");
});
}
I removed the FieldName because your function was named SetAllCheckBoxes, just your input fields are the same. You just need tell what's your form and the state of your checkboxes.
To toggle / refresh checkboxes in jquery mobile you need to use .prop, rather than .attr.
$("input[type='checkbox']").prop("checked",true).checkboxradio("refresh");

How to direct to submit button to another action

how can I jump to another action in controller?
I have form and several submit buttons. Every submmit button has name.
<g:form action="save" method="post">
<g:input name="title" value="${letter.title}" />
<g:input name="comments[0].text" value="${letter.comments[0].text}" />
<g:submitButton name="save" value="save" />
<g:submitButton name="addComment" value="add" />
</g:form>
def save = {
if (params.addComment){
letter.addToComents( new Comment() )
render(view:'form', model:["letter": letter])
return
}
...
if ( letter.save() )
...
}
def addComment = {
...
}
It works, but it is not good. I want move code from block "addComment" to action addComment:
def save = {
if (params.addComment){
// it don´t work
redirect ( action:"addComment" )
}
...
if ( letter.save() )
...
}
def addComment = {
letter.addToComents( new Comment() )
render(view:'form', model:["letter": letter])
return
}
Or it exists better solution?
It would be nice:
<g:submitButton name="save" value="save" action="save" />
<g:submitButton name="addComment" value="add" action="addComment" />
Thanks a lot
Tom
Use the g:actionSubmit tag instead.
<g:form method="post">
<g:input name="title" value="${letter.title}" />
<g:input name="comments[0].text" value="${letter.comments[0].text}" />
<g:actionSubmit action="save" value="Save" />
<g:actionSubmit action="addComment" value="Add Comment" />
</g:form>
For those who are using Twitter Bootstrap plugin (or need something besides text in your button) and want to add a glyphicon to the button, you will need to use the button tag. So you need to do something like
SNIPPET 1.
<g:form role="form" method="post">
...your inputs
<button type="submit" name="_action_save">
<span class="glyphicon glyphicon-ok"></span>
Save
</button>
<button type="submit" name="_action_saveAndNew">
<span class="glyphicon glyphicon-ok"></span>
Save and New
</button>
</g:form>
where in your button you will need to specify the name of your action with the prefix
_action_
to get something like this
name="_action_yourActionName"
just a little reminder, since I am using twitter Bottstrap plugin 3.0 this is how you add a glyphicon
<span class="glyphicon glyphicon-ok"></span>
SNIPPET 1. has a similar behaviour to:
<g:form role="form" method="post">
...your inputs
<g:actionSubmit action="save" value="Save" />
<g:actionSubmit action="saveAndNew" value="Save and New" />
</g:form>
In the end this example help you have a similar behaviour to actionSubmit in cases where you don't want or can't use it. This is only an alternative and it'd be better to use actionSubmit whenever possible.

Multiple forms in ASP.NET MVC

Context
Let`s say i have:
In layout Site.Master:
<div class="leftColumn">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
<div class="rightColumn">
<% Html.RenderPartial("_Login"); %>
<asp:ContentPlaceHolder ID="SideContent" runat="server" />
</div>
Login partialView looks like:
<form action="/myApp/Account/Login" method="post">
<input name="name" />Name<br />
<input name="password" type="password" />Password<br />
<button>Login</button>
</form>
Is it possible to update only login widget form, not the entire content page?
If you are referring to a http post, only a post initiated (it can also be initiated by javascript) by a submit button from within the form will be posted to the server.
If your forms are nested then this won't work. The outer form will always post to the server.
In the sample HTML below, clicking on the submit button on the first form will not send the values from the second form to the server. Likewise, clicking the second submit button won't post the values from the first form.
<html>
...
<body>
<div>
<form action="/Login/Login" method="post">
<input type="text" name="username" value="" />
<input type="text" name="passowrd" value="" />
<input type="submit" name="login" value="Login" />
</form>
<form action="/Login/AdminLogin" method="post">
<input type="text" name="username" value="" />
<input type="text" name="passowrd" value="" />
<input type="submit" name="login" value="Login Admin" />
</form>
</div>
</body>
</html>
If you only wish to update/change one of the form section, then no this can not be done without using javascript and performing a javascript post(aka Ajax).
If you build a controller method that accepts a FormCollection and your view has two forms defined, the formcollection returned will either be populated with values from form A or form B. You can inspect the formCollection and branch your logic based on the value therein. If you want the be very explicit you could have the same hidden variable occur in both forms with a value that would help your make your choice.
That's one approach. there are a few ways to deal with this I'm sure.
If you have two simple forms, you can use this aproach:
You create two different partial views.
#model CustomerInfoModel
#using (Ajax.BeginForm("CustomerInfo", "Customer", new AjaxOptions { HttpMethod = "Post", OnBegin = "InfoLoading", OnComplete = "InfoCompleted" }, new { id = "info", #class = "form-horizontal" }))
{
<input type="text" class="form-control" name="Name" id="Name" value="#Model.Name" />
<input type="email" class="form-control" name="Email" id="Email" value="#Model.Email" />
<button type="submit" id="save-info" class="btn-medium red">Save</button>
}
and
#model CustomerPasswordChangeModel
#using (Ajax.BeginForm("CustomerPasswordChange", "Customer", new AjaxOptions { HttpMethod = "Post", OnBegin = "InfoLoading", OnComplete = "InfoCompleted" }, new { id = "change", #class = "form-horizontal" }))
{
<input type="password" class="form-control" name="OldPassword" id="OldPassword" value="" />
<input type="password" class="form-control" name="NewPassword" id="NewPassword" value="" />
<button type="submit" id="save-change" class="btn-medium red" autocomplete="off">Save</button>
}
In your parent view,
#Html.Partial("CustomerInfo", Model.CustomerInfo)
and
#Html.Partial("CustomerPasswordChange", Model.CustomerPasswordChange)
In Controller:
[HttpPost]
public ActionResult CustomerInfo([Bind(Include = "Name,Email")] CustomerInfoModel model)
{
if (ModelState.IsValid)
return new Json(new { success=true, message="Updated.", errors=null);
// do you logic
return new Json(new { success=false, message="", errors=getHtmlContent(ModelState.Values.SelectMany(v => v.Errors).ToList(), "ModelError"));
}
[HttpPost]
public ActionResult CustomerPasswordChange([Bind(Include = "OldPassword,NewPassword")] CustomerPasswordChangeModel model)
{
if (ModelState.IsValid)
return new Json(new { success=true, message="Updated.", errors=null);
// do you logic
return new Json(new { success=false, message="", errors=getHtmlContent(ModelState.Values.SelectMany(v => v.Errors).ToList(), "ModelError"));
}
This will do what you want to do.
Note: getHtmlContent method is just generating an error message to be displayed on page. Nothing so special. I may share it if required.
Your question is not very clear.
But as far as I could understand, the answer is most likely yes. You can update anything you want depending on the user input.
if(pass != true)
{
ViewData["Message'] = "Hey your login failed!"; Return View("Login")
}
On ViewPage
<form action="/tralala/Account/Login" method="post">
<input name="name" />Name<br />
<input name="password" type="password" />Password<br />
<button>Login</button>
<div style="color: red"><%=ViewData["Message"] %><div>
</form>

Resources