Here is my Grails (2.3.6) controller:
class WidgetController {
def index() {
render(
view: "createNew",
model:[
]
)
}
def execute() {
println "Executing form submission!"
redirect(action: "listAll")
}
def listAll() {
// Does some stuff
}
}
The index URL is, say, http://localhost:8080/myapp/widget. The idea is that when someone goes to this URL, they are presented with an HTML form. When they fill out the form, they are sent (on the server side) to the execute() method, which does some heavy duty stuff and then redirects them to the listAll() method which does some final stuff and renders a web page for them to see.
Here is the HTML form on the createNew.gsp (rendered from the index() method:
<g:form name="create-new-form" url="[action:'execute',controller:'widget']">
<table class="pure-table pure-table-bordered">
<tr>
<td class="row-header">Fizz:</td>
<td><g:textField id="app-fizz" name="fizz" /></td>
</tr>
<tr>
<td class="row-header">Buzz:</td>
<td><g:textField id="app-buzz" name="buzz" /></td>
</tr>
</table>
<g:actionSubmit value="Create" />
</g:form>
When I go to this URL and submit the form (clicking the Create button) I get redirected to http://localhost/myapp/widget/execute which displays one of my customized error pages (basically a "Sorry this page is unavailable"-type error.
Additionally, in the log outputs, my println stating "Executing form submission!" is not firing. This tells me that I don't have something wired correctly: Grails is trying to redirect to an /execute URL but somehow isn't linking that URL with my controller's execute() method. Ideas?
Try with:
<g:actionSubmit action="execute" value="Create" />
If you specify only value for g:actionSubmit it creates button with this label and also redirect to action based on this value. If action name is different than button label you should specify action and value attributes. Take a look at documentation.
Note that if you use g:actionSubmit then action attribute of g:form will be ignored (which you specified btw.). You'll find more info where it may be useful in docs linked above.
use plain <input type="submit" value="go"/>. thus the form is submitted to the URI defined in <g:form> tag
g.actionSubmit or g.submitButton are needed, if you want to submit your form somewhere ELSE.
Related
I have a form which should print questions dynamically. Foo has a Field object and a Field Definition object. I want the Field to have its fieldDefinition assigned by the form. All of the behind the scenes stuff works fine.
The below code works with assigning Strings and Longs in other scenarios.
Here's the line that's causing trouble:
<input th:type="hidden" th:field="*{fields[__${iterationStatus.index}__].fieldDefinition}" th:value="${fooViewModel.fields[__${iterationStatus.index}__].fieldDefinition}"/>
This is what it looks like when it renders in html:
<input type="hidden" value="com.blah.domain.FieldDefinition#fbb2e392" id="fields0.fieldDefinition" name="fields[0].fieldDefinition">
When I submit the form, no controller action is invoked, and the app simply redirects to the error page.
If it's impossible to actually do the assignment that way, please suggest other methods. The only way I came up with is to have Foo use the FieldDefinitionService to do the assignment after being passed an ID. I don't that Domain class to have access to another Domain object's Service.
Thanks
Just an example: when you need to iterate a form inside an element that has a th:each attribute, you can use the following structure (so far, it's the only way that's working for me).
<tr th:each="rank, stat : ${ranks}">
<td th:text="${rank.name}">This is static</td>
<td th:text="${rank.description}">This is static</td>
<td>
<form th:action="#{/user/ranks/delete}" method="post">
<input type="hidden" id="id" name="id" th:value="${rank.id}"></input>
<button class="btn btn-danger" type="submit">
<span>Delete</span>
</button>
</form>
</td>
</tr>
Here ranks is a list of entities that have to be displayed on a table and, for each entity, there is a delete button associated to a form.
The controller method should be similar to the following fragment, the parameter is availabled with the name id:
#RequestMapping(path = "/delete", method = RequestMethod.POST)
public View deleteRank(Model model, #RequestParam(name = "id") String rankId,
#ModelAttribute("user") User user)
{
Long id = Long.parseLong(rankId);
// delete ...
RedirectView redirectView = new RedirectView("/user/ranks");
return redirectView;
}
I use an ajax form for removing items from a list. The first time I submit something, it works but the second times, the reference of the item submitted is not correct: it is the first reference that is still used.
Here is my ajax form:
<div>
<table>
#foreach (var item in Model.ProjectTechnology)
{
<tr>
<td>#Html.DisplayFor(m => item.TechnologyID) </td>
<td>#using (Ajax.BeginForm("RemoveLinkedTechnology", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "AddedTechnologies" })) {
#Html.Hidden("projectID", item.ProjectID)
#Html.Hidden("removedTechnologyID", item.TechnologyID)
<input type="submit" value="Suppr" />
}</td>
</tr>
}
</table>
</div>
Here is the action in my controller:
[HttpPost]
public ActionResult RemoveLinkedTechnology(int projectID, string removedTechnologyID)
{
// some code here...
}
Example:
Lets say I proceed the submitting like this: first submit: AA; second submit: BB.
For the first call: removedTechnologyID contains AA.
For the second call: removedTechnologyID still contains AA.
Any idea?
Thanks
I suspect that in your controller action you are returning a partial view which updates the contents of the <table> you have shown. Now since Html helpers such as Hidden or TextBox first look for values in ModelState before binding and then in the model what happens is that #Html.Hidden("removedTechnologyID", item.TechnologyID) sees that there is a removedTechnologyID="AA" in the model state and completely ignores your model value which is item.TechnologyID. So if you have looked at the DOM after the first AJAX request you would have seen that all hidden fields have the old values inside them.
To fix this you have 3 possibilities:
Clear the item in model state in your controller action:
[HttpPost]
public ActionResult RemoveLinkedTechnology(int projectID, string removedTechnologyID)
{
...
ModelState.Remove("removedTechnologyID");
ModelState.Remove("projectID");
return View(...);
}
Don't use helpers to generate the hidden fields:
<input type="hidden" name="projectID" value="#item.ProjectID" />
<input type="hidden" name="removedTechnologyID" value="#item.TechnologyID" />
Write a custom Html.Hidden helper which will first use the values in the model before looking at modelstate (out of scope for this answer)
I need to update the value of a textField, using a value on the server, based on the value the user chooses in a g:select. In code:
<g:select name="description" from="${momentum.MoneyTransType.prodList}" value="${moneyInstance?.description}"
noSelection="['':'-Select Description-']" onChange="${remoteFunction(action:'setHowMuch', update:[success:'howMuch', failure:'failure'],
params:'\'selection=\' + this.value', options=[asynchronous:false])}"/>
<g:textField id="howMuch" name="howMuch" value="${moneyInstance?.howMuch}"/>
It's not working. If I give the "update:[success:" a div id, all is good, but that's not what I want. I need to allow the user to enter in a free flow description (which I'll have in another textfield), and a free flow amount. I guess I could hide a div and then listen for changes to that div via jQuery, and then update the amount textField. Should I be able to update a textField using the remoteFunction "update" capability or using another grails capability?
Strangely, putting in a temporary 'toHide' div with a jQuery change function isn't working to update the textField, i.e. the following alert, etc, isn't firing:
$('#toHide').change(function() {
alert(" I got changed, value:");
$("#howMuch").text($(this).val());
});
Well, after writing all the below, I reread your question and see you stated you know it works with a div. So the rest of my answer might not be helpful, but what's wrong with using a div? An empty div won't display anything, so you don't need to hide it. So FWIW:
Put your <g:textField ...> in a template.
Add a div where where you want the template to be rendered. In other
words, replace the current <g:textField ..> with <div id=updateme name=updateme></div>
In your setHowMuch action, render the template.
For example, I do:
In view:
<g:select class='setTagtypeValue-class'
name='tagtype-${i}-header'
from="${org.maflt.ibidem.Tagtype.list(sort:'tagtype').groupBy{it.tagtype}.keySet()}"
value="${setTagtypeValue?.tagtype?.tagtype}"
valueMessagePrefix="tagtype"
noSelection="${['null':'Select One...']}"
onchange="${remoteFunction(action:'options', update:'tagtype-options-${i}',
params:'\'tagtype=\' + this.value +\'&i=${i}\'' )}" />
Controller action:
def options = {
def i = params.i ?: 0
def tagtypes = Tagtype.findAllByTagtype(params.tagtype)
render(template:"tagtypeList", model:[tagtypes:tagtypes,i:i])
}
tagypeList Template:
<table>
<tr>
<th></th>
<th><g:message code="tagtype.lookup"
default="Lookup Table" /></th>
<th><g:message code="tagtype.regexpression"
default="Field Rule" /></th>
<th><g:message code="tagtype.uicomponent"
default="UI Component" /></th>
</tr>
<g:each in="${tagtypes}" var="tagtype" status="j">
<tr>
<td><g:radio name="setTagtypesList[${i}].tagtype.id" value="${tagtype.id}"
checked="${(setTagtypeValue?.tagtype?.id == tagtype.id ||
(!setTagtypeValue?.tagtype?.id && j==0))}"></g:radio></td>
<td>${tagtype.lookupTable}</td>
<td>${tagtype.regexpression}</td>
<td><g:message code="${'uicomponent.' + tagtype.uicomponent.id}"
default="${tagtype.uicomponent.uicomponent}" />
</td>
</tr>
</g:each>
</table>
This code is from the metadataset (called field set in the UI) screen in http://www.maflt.org/products/Ibidem.
I'm wondering how I can populate a text box in my view from a list in my controller, I have been searching for examples for awhile, but haven't really found anything. I'm uncertain on how to access the text field from the view exactly, where as in Java you could do something as simple as jTextField.getText(). I'm also wondering on how to grab the text in my text box as well.
Below I'll post some example code of what I'm doing.
Controller:
def loadFile = {
def propFile = "c:/props.txt"
def propMap = [:]
def propList = []
new File(propFile).eachLine { line ->
def (key,value) = line.split(':').collect { it.trim() }
propMap."$key" = "$value"
if(propMap) {
propList << propMap
propMap = [:]
}
}
}
def saveFile = {
//get contents of text box
//over-write props.txt with new information
}
View:
<g:textField name="properties"/>
<span class="menuButton"/><g:link action="loadFile" controller="myController">Load File</g:link>
<span class="menuButton"/><g:link action="saveFile" controller="myController">Save File</g:link>
So, my question seems relatively straight forward, how do I access the text box when I want to populate it and save the data from it?
.
.
.
EDIT
After checking out some of the examples submitted by you guys, I have one last question.
Why does the following code act different when clicking the Load File button?
<g:form controller="drive">
<g:textArea name="properties" value="${params.param1}" rows="50" cols="6"/>
<br/>
<g:submitButton name="loadFile" value="Load File"/>
<g:submitButton name="saveFile" value="Save File"/>
</g:form>
<span class="menuButton"/><g:link action="loadFile" controller="drive">Load File</g:link>
When clicking the g:submitButton dealing with loadFile it redirects me to the list gsp. However, when I click the menuButton it loads the textArea with the text from the file. The reason I ask is because with the second option, the button isn't located where I would like it to be.
Wrap your text field in form tag. This way, when you submit it, you can access your field in controller.
<g:form controller="myController" action="saveFile">
<g:textField name="properties"/>
<g:submitButton name="saveFile" value="Save File" />
</g:form>
Then, you can access your properties field in controller:
def saveFile = {
def properties = params.properties
// do whatever you need
}
EDIT:
To address some of the issues that came up later in comments, I'll try to provide some more insight.
Let's assume that your controller is called Drive and view (the form to submit properties) is drive/properties.gsp. If want your load button to load your properties into the text area, you can do something like this:
def loadFile = {
// your code here
render(view: 'properties.gsp', model=[properties:propList])
}
And in your view:
<g:form controller="drive">
<g:textArea name="properties" value="${properties?.join("\n")}" rows="50" cols="6"/>
<br/>
<g:actionSubmit name="loadFile" action="loadFile" value="Load File"/>
<g:actionSubmit name="saveFile" action="saveFile" value="Save File"/>
</g:form>
This should render your form with values from your file, each property in new line. But I didn't test it.
jjczopek's answer shows how to get access to the data in the controller after it has been submitted from the view.
You can pass a default value through from the controller to the view by setting a parameter in the controller eg...
params.param1 ='value to pass'
render(view:"testView")
Then in your view you can retrieve it again with...
<g:textField name="text1" value="${params.param1}"/>
You may also find this question and these docs useful.
If want to pass domain objects through then one of the following specific render methods might be better...
Grails Controller - Render
I have two submit buttons in one form. I want to call different actions in both buttons. Is there any way to accomplish this without using JavaScript.
Calling different actions is not possible without javascript. You could call the same controller action and inside this action determine which button was pressed using the name property:
<% using (Html.BeginForm()) { %>
<input type="submit" name="save" value="Save" />
<input type="submit" name="update" value="Update" />
<% } %>
and in your controller action:
[HttpPost]
public ActionResult Index(string save)
{
if (!string.IsNullOrEmpty(save))
{
// the save button was pressed
}
else
{
// the update button was pressed
}
return View();
}
Give the buttons different name attributes. Then in your view handler (or equivalent - sorry, not an ASP.NET MVC person), you can check if that button's name is in the HTTP response and act accordingly.
Only one of the submit button names should exist in the response.
Of course there is!
for example, we have following form:
<form>
<input name='customer_name' type='text'/>
<input name='update_user' type='submit' value='Update user info'/>
<input name='delete_user' type='submit' value='Delete user'/>
</form>
when server gets form request there exists only one parameter in the collection: either update_user or delete_user. depends on what user has pressed.