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;
}
Related
In my application, I have search button and based on the search criteria, I have to search data. I have used few hidden variables to store data.
My .gsp page looks like this:
<g:form id="job" name="job" method="POST">
<div>
<input type="hidden" id="country" name="country" value="${country}"/>
<input type="hidden" id="paginationFlag" name="paginationFlag" value="${paginationFlag}"/>
<!-- There are other components like text field, select box etc -->
<g:actionSubmit id="Search" value="Search" formmethod="post" action="findJob"/>
</div>
</g:form>
My respective controller method looks like this:
def findJob(){
def country
def paginationFlag
if(params?.country){
country = params?.country
}else{
country = 'USA'
}
if(params?.paginationFlag){
paginationFlag = params?.paginationFlag
}else{
paginationFlag = 'false'
}
withFormat{
html{
List<Applicant> searchList //get data from database.
// other business logic
render(view : "jobList",model:[paginationFlag: paginationFlag, country:country])
}
json{
// some business logic
def candidateList // value for this candidateList is acquired from database
def json = ['jsn': candidateList]
render json as JSON
}
}
When I click search button and debug the code, first my control goes to controller-> findJob() method and executes the code inside html part.
Secondly, it goes to the gsp page (view page) and sets value.Third, it again goes to the controller and executes the code inside json part.
On the first entry to the controller, the value of paginationFlag and country in param are both null. So it will set the value 'false' and 'USA' respectively. But when control goes to controller again for the second time, again the value of param.paginationFlag and params.country are null. Should not they have the assigned values?
Why is it so? What should I do go get the value of country and paginationFlag in params on the second time? Can any one explain me ? Thank you very much for advance.
The problem is you're using a regular HTML input tag rather than a Grails g:hiddenField tag. Try this:
<g:form id="job" name="job" method="POST">
<div>
<g:hiddenField name="country" value="${country}"/>
<g:hiddenField name="paginationFlag" value="${paginationFlag}"/>
<!-- There are other components like text field, select box etc -->
<g:actionSubmit id="Search" value="Search" formmethod="post" action="findJob"/>
</div>
</g:form>
Tip
You can also simply the params assignment:
def country = params.country ?: 'USA'
def paginationFlag = params.paginationFlag ?: 'false'
I can't tell where the paginationFlag comes from, but know that a boolean is valid.
I'm starting with Grails and I don't know how should I face the following use case.
The app is about sports results prediction, so I have in my domain "Match" and "Prediction", and I want to have one view where the user can update all the predictions of matches that haven't been played yet.
So far I've defined a method in my "PredictionController" that searches all the already existing predictions of games that have to be played and generates new Prediction instances for any new Match with a date higher than now. I've created a view for that method and I'm getting correctly all the predictions that I should complete or update, and I've defined in my controller another method for the form sumbission (so I'm trying to resolve this in the same way that the 'create' and 'update' scaffolded methods work).
My question is, How can I access to all the Predictions modified by my view? How can I send all the predictions to my update method? Is it defining a hidden field with a variable containing all the collection?
This is the form in my GSP view:
<g:form action="savePredicctions">
<fieldset>
<g:each in="${predictions}">
<li>
<div>
${it.match.homeTeam}
<g:field name="${it.match}.homeGoals" type="number" value="${it.homeGoals}" />
</div>
-
<div>
<g:field name="${it.match}.awayGoals" type="number" value="${it.awayGoals}" />
${it.match.awayTeam}
</div>
</li>
</g:each>
</fieldset>
<fieldset class="submit">
<g:submitButton />
</fieldset>
</g:form>
You can use a command object to store the instances of Prediction.
#Validateable
class PredictionCommand {
//data binding needs a non-null attribute, so we use ListUtils.lazyList
List<Prediction> predictions = ListUtils.lazyList([], FactoryUtils.instantiateFactory(Prediction))
}
In your view, you need to control the index of your list, and send the attributes of Prediction to the controller:
<g:each in="${predictions}" status="i">
<g:textField name="predictions[$i].homeGoals" />
<g:textField name="predictions[$i].awayGoals" />
</g:each>
And in your controller you can use bindData() to bind params to your command:
class CommandController {
def save() {
PredictionCommand command = new PredictionCommand()
bindData(command, params)
println command.predictions
}
}
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 have 2 forms in my myPage.chtml page as follows:
#using (Html.BeginForm("Tests1", "Test", FormMethod.Post, new { id = "FormSearch1" }))
{
<input type ="submit" value="Filter1 " id="submit" />
}
and another form as follows:
#using (Html.BeginForm("Tests2", "Test", FormMethod.Post, new { id = "FormSearch2" }))
{
<input type ="submit" value="Filter2 " id="submit" />
}
However, I am having the error message and it`s not working upin clicking the submit buttons. What am I missing?
Warning 2 Another object on this page already uses ID 'submit'.
In your example, you have two <input> elements that have the same id="submit" attribute. id should be unique on each HTML page. To solve the problem, either remove the id attribute completely (if it is not actually used), or use different values.
If you need to have these submit buttons to have the same name but different values (considering the different Actions and ids submit in your example, I doubt that), you could try to use <input type="submit" value="Filter1" name="submit"/> and <input type="submit" value="Filter2" name="submit"/> instead.
Simple
You have 2 <input> tags with the same id submit.
I have an HTML table where each row has buttons which toggle status bits in the database for each row. Assuming Javascript is not an option, what would be the "best practice" way of handling this?
I'm currently handling it by wrapping each row in a form like this:
<table>
<tr>
<td>
<form action="/FooArea/BarController/BazAction" id="frm0" name="frm0" method="post">
<span>Item 1</span>
<input type="submit" value="Toggle1" name="submitButton" />
<input type="submit" value="Toggle2" name="submitButton" />
<input type="hidden" name="itemID" value="1" />
</form>
</td>
</tr>
<tr>
<td>
<form action="/FooArea/BarController/BazAction" id="frm1" name="frm1" method="post">
<span>Item 2</span>
<input type="submit" value="Toggle1" name="submitButton" />
<input type="submit" value="Toggle2" name="submitButton" />
<input type="hidden" name="itemID" value="2" />
</form>
</td>
</tr>
</table>
And the post method looks something like this:
string buttonName = Request.Form["submitButton"];
if (!String.IsNullOrEmpty(buttonName ))
{
int itemID = Convert.ToInt32(Request.Form["itemID"]);
switch (buttonName )
{
case "Toggle1":
DoSomething(itemID);
break;
case "Toggle2":
DoSomethingElse(itemID);
break;
}
}
Any better suggestions? Is having 50 forms on a page cool? I dunno.. let me know what you are doing in this case.
The best way to handle POST scenarios without JavaScript is, as several others have stated, a tiny form with only the necessary values, and only one submit button. Basically, what you should do is to create a helper method that creates a form with the necessary POST values in hidden fields and a submit button. For example, you could have a method you use like this:
<%= Html.PostLink("FooArea/BarController/BazAction", "Toggle1", new List<KeyValuePair<string, string>>{ new KeyValuePair<string, string>("itemId", 1), new KeyValuePair("action", "option1") }); %>
It looks pretty verbose, but I've tried to make it as generic as possible. You can probably create the List<KeyValuePair<string, string>> in the controller when you render the view, so you only have to call something
<%= Html.PostLink("FooArea/BarController/BazAction", "Toggle1", Model.Values) %>
In the action method that handles the post, you bind to the posted FormCollection, and retrieve the values of itemId and action to determine what to do, instead of checking for Request.Form values.
An implementation of the helper method might look like this:
public static string PostLink(this HtmlHelper helper, string postAction, string submitText, IEnumerable<KeyValuePair<string, string>> postValues)
{
var form = new TagBuilder("form");
// Setup basic properties like method, action
form.Attributes.Add("method", "post");
form.Attributes.Add("action", postAction);
// Instantiate a stringbuilder for the inner html of the form
var innerHtml = new StringBuilder();
// Create and append hidden fields for the post values
foreach(var value in postValues)
{
var hidden = new TagBuilder("input");
hidden.Attributes.Add("type", "hidden");
hidden.Attributes.Add("name", value.Key);
hidden.Attributes.Add("value", value.Value);
innerHtml.Append(hidden.ToString(TagRenderMode.SelfClosing));
}
// Create the submit button
var submit = new TagBuilder("input");
submit.Attributes.Add("type", "submit");
submit.Attributes.Add("value", submitText);
// Append it to the stringbuilder
innerHtml.Append(submit.ToString(TagRenderMode.SelfClosing));
// Set the InnerHtml property of the form, and return it
form.InnerHtml = innerHtml.ToString();
return form.ToString(TagRenderMode.Normal);
}
This seems like a prime case for some JQuery and Ajax functionality. But if javascript isn't an option then i think wrapping each one in a form is probably the most simple solution.
When I need to do something like this I do it pretty much the same way as you do here. It is no problem to have multiple forms in one view. Its like having multiple links in one view (but they use POST instead of GET). I guess many .net developers think its wrong because of webforms only having one form tag. In your case I would even create more forms for each submit button as they seem to do different things. I consider having to check the name of the button in the controller to be a code smell. If they do something like activate/deactivate you should probably post that as a bool or something and have both forms post to the same action.
I think technically this is the best way to go. From a usability point of view you can question if this is the best way to do it. More than 20 items in a list can get quite confusing. But ofcourse, I don't really know what you are programming :)
I agree with Mattias about creating different actions for the activate and deactivate-button. This way you avoid having to use a switch-statement.