What are some handy tricks for submitting Grails forms? - forms

Everybody's aware of passing parameters to a controller via a html form:
<g:form action="save">
<g:textField name="text1" />
</g:form>
And I'm vaguely aware of being able to structure these parameters into some sort of object notation in Grails:
<g:form action="save">
<g:textField name="text.a" />
<g:textField name="text.b" />
</g:form>
With very little idea how they are structured in the controller (objects? hashmaps? I recall having to use .value at some point using the latter example).
So I guess this question is really two questions:
How does Grails handle parameters in object notation like the second example? Can you stick them into arrays too?
What are some other tricks regarding form submission and its parameters that can make forms with very complex and iterative data trivial to handle in the controller? For instance, ATG allows you to bind form fields to beans and walk its entire property graph to find the property you need to set.

The second notation "text.a" is used to disambiguate data conversion from properties to domain objects. For example, if you have 2 domain objects each with a property "a", if you do domObj1.properties = params and domObj2.properties = params the value will go to both domain objects which may not be what you want. So in your view you should have variables domObj1.a and domObj2.a and in your grails controller you can instantiate using def domObj1 = new DomObj1(params["domObj1"])
By your second question if you mean whether you can iterate over objects, you very well can, using GPath syntax in a ${} wrapper, for e.g check out the code in the id property below.
<td><g:remoteLink controller="device" action="getDevice" id="${objInstance.prop1.prop2.id}" update="propDetail">${fieldValue(bean: objInstance.prop1, field: "prop1")}</g:remoteLink></td>
The example above also shows an ajax way of form submission from grails gsp.

Related

Is using [(ngModel)] in reactive forms bad practice?

I'm starting to use model based forms in my angular App. So far I have been suing template based forms and I bind my data using [(ngModel)].
I noticed that using [(ngModel)] in reactive forms is possible, but I've been reading on stack that it's a bad practice, but I can't find (or missed) anything about this in the docs.
Is it true that you should avoid using when you are working with reactive forms? If so, what would be the correct way to bind data to an input?
Right now I do something like this:
My component:
this.assignForm = this.fb.group({
"balance": [null, Validators.required]
});
My Template
<input type="text" formControlName="balance" [(ngModel)]="myData.Balance" />
Every HTML input element is wrapped by an angular class called FormControl. FormBuilder creates the FormControls explicitly. Putting NgModel on a element will also create a FormControl.
In your example, you have two FormControl objects for the same element.
Assuming they don't fail due to name clash (like <input name="myname" formControlName="myname" [(ngModel)]="model.prop" /> would register myname with the FormGroup twice), then you might get different answers on valid/invalid/touched/dirty depending on which one was queried.
Your question title and question completely mix up model based and reactive, where your code uses them both combined. Using both combined results in absolutely no guarantee that the value you see and the value your form controller contains are equal. Just do not do it.
The correct way would be:
this.assignForm = this.fb.group({
"balance": [myData.Balance, Validators.required]
});

Auto populate form input based on name?

If I have a Command Object such as
class AppContactInfoCommand {
String fname = "Tom";
}
When I pass that command object to my view to populate my form I have to do this
<g:textField name="cmd.fname" value="${cmd.fname}"/>
This just seems extremely repetitive and time consuming if I have large forms with many fields. Isn't there any way to to have the g:textField intelligently detect that value and auto-populate the value field so all I have to do is
<g:textField name="cmd.fname" />
Other frameworks I have worked with do this so Im sure there must be a way from Grails to do this too.
Grails Version: 3.1
There is nothing stopping you from writing your own tag library to do just that. However the included tag libraries for such things as the textField do not have this behavior. As can be seen from the documentation.

grails access form attributes in controller

In grails i have a form with g:field tags like:
<g:field name="test" from="0..20"/>
I am trying to find a way how I can access the "from" attribute in my controller.
I can get the "value" attribute by using:
print params.test
I have tried:
print params.test.from
I'm sure there must be a way to do this but I can not seem to find it.
What I am wanting to achieve by this is perform validation so that the value does not go outside the the from range.
I know that this can be added in the domain, but in my situation I need to allow the user to overwrite the range constraints.
Any ideas?
By the time that code hits the browser, it is just HTML. from doesn't exist anymore. If that is being rendered into some sort of client side validation, that's not going to get submitted back to the server in a form submit.
If you explain what you are really needing to do in your question, I can provide a better answer.
You can pass the "from" values as hidden fields.
<g:hiddenField name="min" value="0" />
<g:hiddenField name="max" value="20" />
Something like that.

Set class or ID on <h:inputHidden> in JSF

I'm trying to set a class or id parameter on a <h:inputHidden> in JSF. The code looks like this:
<h:inputHidden value="#{getData.name}" class="targ" />
But in the browser, the class isn't set:
<input type="hidden" name="j_idt6" value="j_idt6">
I need to set a class to this parameter, because I have a JavaScript autocomplete function for a <h:inputText> that sets a value in the hidden input, which needs to be passed in the next page.
Any ideas? Thanks!
I know it's a little bit late, but it can help someone in the future.
As inputHidden shows nothing in the browser there's no sense to allow it to have a class.
You can use the Id but as the Id could change as you change the component parents using it would bring some headache.
I'd suggest as a workaround, you can give it a parent so you can manipulate it by javascript.
Exemple:
JSF
<h:panelGroup styleClass="someCssClass">
<h:inputHidden id="someId" value="someValue" />
</h:panelGroup>
Javascript (using jQuery, you could use pure javascript also)
$('.someCssClass input[type=hidden]').val('yourNewValue');
None of these answers here satisfied my needs (need the PrimeFaces component, need class not ID, wrapping is too much work), so here's what I came up with:
Use pass-through attributes: https://www.primefaces.org/jsf-2-2-pass-through-attributes
Use pass:hidden-class="blah" (in my case, it's xmlns:pass up top)
Use [attribute=value] selector:
https://www.w3schools.com/cssref/sel_attribute_value.asp
document.querySelector multiple data-attributes in one element
That basically boils down to using something like this (because h:inputHidden becomes a regular input): document.querySelector("input[hidden-class=" + blah + "]")
Please, see similar question - How can I know the id of a JSF component so I can use in Javascript
You can sed "id" property, but in final html code it can be not the same, but composite: for example, if your input with id="myhidden" is inside form with id="myform", final input will have id="myform:myhidden".
In the end, I used a standard HTML <input type="hidden"> tag, as I had no advantages for using the JSF one. If you're trying to set a value in a hidden input with JavaScript, I recommend using this workaround.

What's the best/most RESTful way to simulate a procedure call over HTTP?

I have a service that takes an .odt template file and some text values, and produces an .odt as it's output. I need to make this service available via HTTP, and I don't quite know what is the most RESTful way to make the interface work.
I need to be able to supply the template file, and the input values, to the server - and get the resulting .odt file sent back to me. The options I see for how this would work are:
PUT or POST the template to the server, then do a GET request, passing along the URI of the template I just posted, plus the input values - the GET response body would have the .odt
Send the template and the parameters in a single GET request - the template file would go in the GET request body.
Like (2) above except do the whole thing as a single POST request instead of GET.
The problem with (1) is that I do not want to store the template file on the server. This adds complexity and storing the file is not useful to me beyond the fact that it's a very RESTful approach. Also, a single request would be better than 2, all other things being equal.
The problem with (2) is that putting a body in a GET request is bordering on abuse of HTTP - it is supported by the software I'm using now, but may not always be.
Number (3) seems misleading since this is more naturally a 'read' or 'get' operation than a 'post'.
What I am doing is inherently like a function call - I need to pass a significant amount of data in, and I am really just using HTTP as a convenient way of exposing my code across the network. Perhaps what I'm trying to do is inherently un-RESTful, and there is no REST-friendly solution? Can anyone advise? Thank you!
Wow, so this answer escalated quickly...
Over the last year or so I've attempted to gain a much better understanding of REST through books, mailing lists, etc. For some reason I decided to pick your question as a test of what I've learned.
Sorry :P
Let's make this entire example one step simpler. Rather than worry about the user uploading a file, we'll instead assume that the user just passes a string. So, really, they are going to pass a string, in addition to the arguments of characters to replace (a list of key/values). We'll deal with the file upload part later.
Here's a RESTful way of doing it which doesn't require anything to be stored on the server. I will use some HTML (albeit broken, I'll leave out stuff like HEAD) as my media type, just because it's fairly well known.
A Sample Solution
First, the user will need to access our REST service.
GET /
<body>
<a rel="http://example.com/rels/arguments" href="/arguments">
Start Building Arguments
</a>
</body>
This basically gives the user a way to start actually interacting with our service. Right now they have only one option: use the link to build a new set of arguments (the name/value pairings that will eventually be used to in the string replacement scheme). So the user goes to that link.
GET /arguments
<body>
<a rel="self" href="/arguments"/>
<form rel="http://example.com/rels/arguments" method="get" action="/arguments?{key}={value}">
<input id="key" name="key" type="text"/>
<input id="value" name="value" type="text"/>
</form>
<form rel="http://example.com/rels/processed_string" action="/processed_string/{input_string}">
<input id="input_string" name="input_string" />
</form>
</body>
This brings us to an instance of an "arguments" resource. Notice that this isn't a JSON or XML document that returns to you just the plain data of the key/value pairings; it is hypermedia. It contains controls that direct the user to what they can do next (sometimes referred to allowing the user to "follow their nose"). This specific URL ("/arguments") represents an empty list of key/value pairings. I could very well have named the url "/empty_arguments" if I wanted to: this is an example why it's silly to think about REST in terms of URLs: it really shouldn't matter what the URL is.
In this new HTML, the user is given three different resources that they can navigate to:
They can use the link to "self" to navigate to same resource they are currently on.
They can use the first form to navigate to a new resource which represents an argument list with the additional name/value pairing that they specify in the form.
They can use the second form to provide the string that they wish to finally do their replacement on.
Note: You probably noticed that the second form has a strange "action" url:
/arguments?{key}={value}
Here, I cheated: I'm using URI Templates. This allows me to specify how the arguments are going to be placed onto the URL, rather than using the default HTML scheme of just using <input-name>=<input-value>. Obviously, for this to work, the user can't use a browser (as browsers don't implement this): they would need to use software that understands HTML and URI templating. Of course, I'm using HTML as an example, your REST service could use some kind of XML that supports URI Templating as defined by the URI Template spec.
Anyway, let's say the user wants to add their arguments. The user uses the first form (e.g., filling in the "key" input with "Author" and the "value" input with "John Doe"). This results in...
GET /arguments?Author=John%20Doe
<body>
<a rel="self" href="/arguments?Author=John%20Doe"/>
<form rel="http://example.com/rels/arguments" method="get" action="/arguments?Author=John%20Doe&{key}={value}">
<input id="key" name="key" type="text"/>
<input id="value" name="value" type="text"/>
</form>
<form rel="http://example.com/rels/processed_string" action="/processed_string/{input_string}?Author=John%20Doe">
<input id="input_string" name="input_string" />
</form>
</body>
This is now a brand new resource. You can describe it as an argument list (key/value pairs) with a single key/value pair: "Author"/"John Doe". The HTML is pretty much the same as before, with a few changes:
The "self" link now points to current resources URL (changed from "/arguments" to "/arguments?Author=John%20Doe"
The "action" attribute of the first form now has the longer URL, but once again we use URI Templates to allow us to build a larger URI.
The second form
The user now wants to add a "Date" argument, so they once again submit the first form, this time with key of "Date" and a value of "2003-01-02".
GET /arguments?Author=John%20Doe&Date=2003-01-02
<body>
<a rel="self" href="/arguments?Author=John%20Doe&Date=2003-01-02"/>
<form rel="http://example.com/rels/arguments" method="get" action="/arguments?Author=John%20Doe&Date=2003-01-02&{key}={value}">
<input id="key" name="key" type="text"/>
<input id="value" name="value" type="text"/>
</form>
<form rel="http://example.com/rels/processed_string" action="/processed_string/{input_string}?Author=John%20Doe">
<input id="input_string" name="input_string" />
</form>
</body>
Finally, the user is ready to process their string, so they use the second form and fill in the "input_string" variable. This once again uses URI Templates, thus having bringing the user to the next resource. Let's say that that the string is the following:
{Author} wrote some books in {Date}
The results would be:
GET /processed_string/%7BAuthor%7D+wrote+some+books+in+%7BDate%7D?Author=John%20Doe&Date=2003-01-02
<body>
<a rel="self" href="/processed_string/%7BAuthor%7D+wrote+some+books+in+%7BDate%7D?Author=John%20Doe&Date=2003-01-02">
<span class="results">John Doe wrote some books in 2003-01-02</span>
</body>
PHEW! That's a lot of work! But it's (AFAIC) RESTful, and it fulfills the requirement of not needing to actually store ANYTHING on the server side (including the argument list, or the string that you eventually want to process).
Important Things to Note
One thing that is important here is that I wasn't just talking about URLs. In fact, the majority of time, I'm talking about the HTML. The HTML is the hypermedia, that that's is such a huge part of REST that is forgotten about. All those APIs that say they are "restful" where they say "do a GET on this URL with these parameters and POST on this URL with a document that looks like this" are not practicing REST. Roy Fielding (who literally wrote the book on REST) made this observation himself.
Another thing to note is that it was quite a bit of pain to just set up the arguments. After the initial GET / to get to the root (you can think of it as the "menu") of the service, you would need to do five more GET calls just to build up your argument resource to make an argument resource of four key/value pairings. This could be alleviated by not using HTML. For example, I already did use URI Templates in my example, there's no reason to say that HTML just isn't good enough for REST. Using a hypermedia format (like some derivation of XML) that supports something similar to forms, but with the ability to specify "mappings" of values, you could do this in one go. For example, we could extend the HTML media type to allow another input type called "mappings"...
So long as the client using our API understands what a "mappings" input type is, they will be able to build their arguments resource with a single GET.
At that point, you might not even need an "arguments" resource. You could just skip right to the "processed_string" resource that contains the mapping and the actual string...
What about file upload?
Okay, so originally you mentioned file uploads, and how to get this without needing to store the file. Well, basically, we can use our existing example, but replace the last step with a file.
Here, we are basically doing the same thing as before, except we are uploading a file. What is important to note is that now we are hinting to the user (through the "method" attribute on the form) that they should do a POST rather than a GET. Note that even though everywhere you hear that POST is a non-safe (it could cause changes on the server), non-idempotent operation, there is nothing saying that it MUST be change state on the server.
Finally, the server can return the new file (even better would be to return some hypermedia or LOCATION header with a link to the new file, but that would require storage).
Final Comments
This is just one take on this specific example. While I hope you have gained some sort of insight, I would caution you to accept this as gospel. I'm sure there have been things that I have said that are not really "REST". I plan on posting this question and answer to the REST-Discuss Mailing List and see what others have to say about it.
One main thing I hope to express through this is that your easiest solution might simply be to use RPC. After all, what was your original attempt at making it RESTful attempting to accomplish? If you are trying to be able to tell people that you accomplish "REST", keep in mind that plenty of APIs have claimed themself "RESTful" that have really just been RPC disguised by URLs with nouns rather than verbs.
If it was because you have heard some of the benefits of REST, and how to gain those benefits implicitly by making your API RESTful, the unfortunate truth is that there's more to REST than URLs and whether you GET or POST to them. Hypermedia plays a huge part.
Finally, sometimes you will encounter issues that mean you might do things that SEEM non-RESTful. Perhaps you need to do a POST rather than a GET because the URI (which have a theoretical infinite amount of storage, but plenty of technical limitations) would get too long. Well then, you need to do POST. Maybe
More resources:
REST-Discuss
My e-mail on this answer to REST-Discuss
RESTful Web Services Cookbook
Hypermedia APIs with HTML5 and Node (Not specifically about REST, but a VERY good introduction to Hypermedia)
What you are doing is not REST-ful - or, at least, is difficult to express in REST, because you are thinking about the operation first, not the objects first.
The most REST-ful expression would be to create a new "OdtTemplate" resource (or get the URI of an existing one), create a new "SetOfValues" resource, then create a "FillInTemplateWithValues" job resource that was tied to both those inputs, and which could be read to determine the status of the job, and to obtain a pointer to the final "FilledInDocument" object that contained your result.
REST is all about creating, reading, updating, and destroying objects. If you can't model your process as a CRUD database, it isn't really REST. That means you do need to, eg, store the template on the server.
You might be better off, though, just implementing an RPC over HTTP model, and submitting the template and values, then getting the response synchronously - or one of the other non-REST patterns you named... since that is just what you want.
If there is no value in storing the templates then option 2 is the most RESTful, but as you are aware there is the possibility of having your GET body dropped.
However, if I was a user of this system, I would find it very wasteful to have to upload the template each time I would like to populate it with values. Instead it would seem more appropriate to have the template stored and allow different requests with different values to populate the resulting documents.