How to direct to submit button to another action - grails

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.

Related

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

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>

Grails form submit generating blank entry at "params"

I have this form and when the user types something this is submitted as finalAnswer, as you can see below:
<g:form controller="animais" params="['rootNode': rootNode, 'finalAnswer': finalAnswer]">
<h3>${curQuestion} </h3>
<g:if test="${finished}">
<g:actionSubmit class="btn btn-primary" action="backToStart" value="Voltar" />
</g:if>
<g:if test="${!finished}">
<g:if test="${!showDivTip}">
<g:textField name="finalAnswer" value="${finalAnswer}"/>
<g:actionSubmit class="btn btn-primary" action="submitFinalAnswer" value="OK" />
</g:if>
<g:if test="${showDivTip}">
<g:textField name="tipToFinalAnswer" value="${tipText}"/>
<g:actionSubmit class="btn btn-primary" action="submitTipForAnswer" value="Finalizar" />
</g:if>
</g:if>
</g:form>
The problem is that finalAnswer come to params as a 2-sized array of strings, even if the content is a simple string.
When I printed params:
[finalAnswer:[, leao marinho], rootNode:2, _action_submitFinalAnswer:OK, action:index, format:null, controller:animais]
Value of params.finalAnswer: [, leao marinho]
ClassType of params.finalAnswer: class [Ljava.lang.String;
How can I retrieve params.finalAnswer as a simple string?
Try this
<g:form controller="animais" params="['rootNode': rootNode]">
<h3>${curQuestion} </h3>
<g:if test="${finished}">
<g:actionSubmit class="btn btn-primary" action="backToStart" value="Voltar" />
</g:if>
<g:if test="${!finished}">
<g:if test="${!showDivTip}">
<g:textField name="finalAnswer" value="${params.finalAnswer}"/>
<g:actionSubmit class="btn btn-primary" action="submitFinalAnswer" value="OK" />
</g:if>
<g:if test="${showDivTip}">
<g:textField name="tipToFinalAnswer" value="${params.tipText}"/>
<g:actionSubmit class="btn btn-primary" action="submitTipForAnswer" value="Finalizar" />
</g:if>
</g:if>
</g:form>
Answer by #quindimildev not fully right. Better will be use hidden field:
<g:form controller="animais">
<g:hiddenField name="rootNode" value="${rootNode}"/>
<g:hiddenField name="finalAnswer" value="${finalAnswer}"/>
<h3>${curQuestion} </h3>
<g:if test="${finished}">
<g:actionSubmit class="btn btn-primary" action="backToStart" value="Voltar" />
</g:if>
<g:if test="${!finished}">
<g:if test="${!showDivTip}">
<g:textField name="finalAnswer" value="${finalAnswer}"/>
<g:actionSubmit class="btn btn-primary" action="submitFinalAnswer" value="OK" />
</g:if>
<g:if test="${showDivTip}">
<g:textField name="tipToFinalAnswer" value="${tipText}"/>
<g:actionSubmit class="btn btn-primary" action="submitTipForAnswer" value="Finalizar" />
</g:if>
</g:if>
</g:form>
So you can remove it from params. Really, it more clear.

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

I have a basic form for which I want to handle buttons inside the form by calling the ActionResult method in the View's associated Controller class. Here is the following HTML5 code for the form:
<h2>Welcome</h2>
<div>
<h3>Login</h3>
<form method="post" action= <!-- what goes here --> >
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
</form>
</div>
<!-- more code ... -->
The corresponding Controller code is the following:
[HttpPost]
public ActionResult MyAction(string input, FormCollection collection)
{
switch (input)
{
case "Login":
// do some stuff...
break;
case "Create Account"
// do some other stuff...
break;
}
return View();
}
you make the use of the HTML Helper and have
#using(Html.BeginForm())
{
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
}
or use the Url helper
<form method="post" action="#Url.Action("MyAction", "MyController")" >
Html.BeginForm has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:
#using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
< ... >
}
If you don't specify any arguments, the Html.BeginForm() will create a POST form that points to your current controller and current action. As an example, let's say you have a controller called Posts and an action called Delete
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
return View(model);
}
[HttpPost]
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
if(model != null)
db.DeletePost(id);
return RedirectToView("Index");
}
and your html page would be something like:
<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>#Model.Title</strong> will be deleted.</p>
#using(Html.BeginForm())
{
<input type="submit" class="btn btn-danger" value="Delete Post"/>
<text>or</text>
#Url.ActionLink("go to list", "Index")
}
Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.
<a href="Controller/ActionMethod">
<input type="button" value="Click Me" />
</a>
Adding parameters:
<a href="Controller/ActionMethod?userName=ted">
<input type="button" value="Click Me" />
</a>
Adding parameters from a non-enumerated Model:
<a href="Controller/ActionMethod?userName=#Model.UserName">
<input type="button" value="Click Me" />
</a>
You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!

Hide/Disable submit button from controller

How can I hide a webform button from controller action? or Do I do it in webform itself?
There is a condition to hide/disable the button:
if (StudentType != "Senior")
{
Hide Button
}
Display Button
View:
<form method="post" action="/Student/Dispatch/">
<label for="id">Student Number: </label>
<input type="text" name="id" value="" /> <br /><br />
<input type="submit" value="Get Student(xls)" name="xls" /> &nbsp
<input type="submit" value="Get Student(pdf)" name="pdf" />
</form>
Controller:
[HttpPost]
public ActionResult Dispatch(string pdf, string id) {
if (!string.IsNullOrEmpty(pdf)) {
// GetPdf submit button was clicked
return StudentPdf(id);
}
// GetXls submit button was clicked
return StudentExcel(id);
}
You can use ViewData dictionary .
Controller:
if (StudentType != "Senior")
{
ViewData["isHideButton"] =true;
}
View:
<form method="post" action="/Student/Dispatch/">
<label for="id">Student Number: </label>
<input type="text" name="id" value="" /> <br /><br />
<% bool hideButton= false;
bool.TryParse(ViewData["isHideButton"],hideButton)%>
<%if(!hideButton)
{%>
<input type="submit" value="Get Student(xls)" name="xls" />
<%}%>
&nbsp <input type="submit" value="Get Student(pdf)" name="pdf" />
</form>

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