Thymeleaf - how to chose not null object in form - thymeleaf

Trying to check if object is not null in form:
<form th:action="#{register}" th:object="${loginInfo != null ? loginInfo.account : account}" method="post">
<input th:field="*{phoneNumber}"/>
If loginInfo defined and not null I want to use loginInfo.account in form.
Otherwise I want to use account object.
How to do that?
In example above I get IllegalStateException: Neither BindingResult nor plain target object for bean name 'loginInfo!= null ? loginInfo' available as request attribute

Here is what I would do. Since we can't add a conditionals inside a th:object, then the only other way to achieve this, is using a th:block with a th:if. Of course, this will mean that you need your form's inputs in a template, otherwise you will have to duplicate code. I am assuming of course that loginInfo.account have the same fields as account.
First, let's create our template inside our layouts folder. For this example, this html file will be called form-inputs.
<th:block th:fragment="form-inputs">
<input th:field="*{phoneNumber}"/>
</th:block>
Now, the page will have the following code to decide which object to use. If loginInfo is not null, then we will use it's account information, otherwise, we will use account.
<th:block th:if="${loginInfo!=null}">
<form th:action="#{register}" th:object="${loginInfo.account}" method="post">
<section th:replace="layouts/form-inputs :: form-inputs" th:remove="tag">
</section>
</form>
</th:block>
<th:block th:if="${loginInfo == null}">
<form th:action="#{register}" th:object="${account}" method="post">
<section th:replace="layouts/form-inputs :: form-inputs" th:remove="tag">
</section>
</form>
</th:block>
Hope this helps you!

Related

How do I do a POST back on a element event such as <select ... onchange....> [duplicate]

I have a form with id theForm which has the following div with a submit button inside:
<div id="placeOrder"
style="text-align: right; width: 100%; background-color: white;">
<button type="submit"
class='input_submit'
style="margin-right: 15px;"
onClick="placeOrder()">Place Order
</button>
</div>
When clicked, the function placeOrder() is called. The function changes the innerHTML of the above div to be "processing ..." (so the submit button is now gone).
The above code works, but now the problem is that I can't get the form to submit! I've tried putting this in the placeOrder() function:
document.theForm.submit();
But that doesn't work.
How can I get the form to submit?
Set the name attribute of your form to "theForm" and your code will work.
You can use...
document.getElementById('theForm').submit();
...but don't replace the innerHTML. You could hide the form and then insert a processing... span which will appear in its place.
var form = document.getElementById('theForm');
form.style.display = 'none';
var processing = document.createElement('span');
processing.appendChild(document.createTextNode('processing ...'));
form.parentNode.insertBefore(processing, form);
It works perfectly in my case.
document.getElementById("form1").submit();
Also, you can use it in a function as below:
function formSubmit()
{
document.getElementById("form1").submit();
}
document.forms["name of your form"].submit();
or
document.getElementById("form id").submit();
You can try any of this...this will definitely work...
I will leave the way I do to submit the form without using the name tag inside the form:
HTML
<button type="submit" onClick="placeOrder(this.form)">Place Order</button>
JavaScript
function placeOrder(form){
form.submit();
}
You can use the below code to submit the form using JavaScript:
document.getElementById('FormID').submit();
<html>
<body>
<p>Enter some text in the fields below, and then press the "Submit form" button to submit the form.</p>
<form id="myForm" action="/action_page.php">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="button" onclick="myFunction()" value="Submit form">
</form>
<script>
function myFunction() {
document.getElementById("myForm").submit();
}
</script>
</body>
</html>
HTML
<!-- change id attribute to name -->
<form method="post" action="yourUrl" name="theForm">
<button onclick="placeOrder()">Place Order</button>
</form>
JavaScript
function placeOrder () {
document.theForm.submit()
}
If your form does not have any id, but it has a class name like theForm, you can use the below statement to submit it:
document.getElementsByClassName("theForm")[0].submit();
I have came up with an easy resolve using a simple form hidden on my website with the same information the users logged in with. Example: If you want a user to be logged in on this form, you can add something like this to the follow form below.
<input type="checkbox" name="autologin" id="autologin" />
As far I know I am the first to hide a form and submit it via clicking a link. There is the link submitting a hidden form with the information. It is not 100% safe if you don't like auto login methods on your website with passwords sitting on a hidden form password text area...
Okay, so here is the work. Let’s say $siteid is the account and $sitepw is password.
First make the form in your PHP script. If you don’t like HTML in it, use minimal data and then echo in the value in a hidden form. I just use a PHP value and echo in anywhere I want pref next to the form button as you can't see it.
PHP form to print
$hidden_forum = '
<form id="alt_forum_login" action="./forum/ucp.php?mode=login" method="post" style="display:none;">
<input type="text" name="username" id="username" value="'.strtolower($siteid).'" title="Username" />
<input type="password" name="password" id="password" value="'.$sitepw.'" title="Password" />
</form>';
PHP and link to submit form
<?php print $hidden_forum; ?>
<pre>Forum</pre>

how to render a response to a specific place on a gsp grails

I am new to grails and groovy.
I am trying to find out how to render a response from an action in a grails controller IN THE SAME gsp - but in a DIFFERENT SECTION OF THE gsp - as the gsp that takes the request (in this case a web form gsp page)?
any links or turorials or just straight to the point "do this" kind of replies are welcomed.
I tried to google search for it, but I was not sure what to use as a search term and I could not find a concise answer.
========= UPDATE TO QUESTION (INCLUDING SOME CODE) =========
Here is the code I am working with. It is a Grails application in which I am using a bootstrap template (available for free on the internet of course).
Now the actual code itself for functionality works. What I am having an issue with is this:
I have a gsp page that uses a css template and another gsp temlate for layout. I can start the page as inside the gsp+css tempate using this code (snippet) in my gsp page:
<g:layoutBody/>
This allows me to call my calling controller code in this gsp file for the request:
<body>
<g:form name="form" controller="apiStart" id="form">
<div><g:select name="protocolType" value="restCall" from="${["-select-", "GET", "POST", "PUT", "DELETE"]}"/> &nbsp <label>URL: </label><g:textField name="url" value="${url}" />
&nbsp <label>username: </label><g:textField name="userName" value="${userName}" /> &nbsp <label>password: </label><g:textField name="passWord" value="${passWord}" /></div>
%{--<div class="text-field"><label>URL: </label><g:textField name="url" value="${url}" /></div>--}%
%{--<div class="text-field"><label>username: </label><g:textField name="userName" value="${userName}" /></div>
<div class="text-field"><label>password: </label><g:textField name="passWord" value="${passWord}" /></div>--}%
<br>
<div><label>Use Advanced Parameters?</label><g:checkBox name="useAdvParms" value="${false}" /></div>
<div class="text-field"><label>Header1: </label><g:textField name="header1" value="${header1}" /> &nbsp <label>Value1: </label><g:textField name="value1" value="${header2}" /></div>
%{--<div class="text-field"><label>Value1: </label><g:textField name="value1" value="${header2}" /></div>--}%
<div class="text-field"><label>Header2: </label><g:textField name="header2" value="${header3}" /> &nbsp <label>Value2: </label><g:textField name="value2" value="${header4}" /></div>
%{--<div class="text-field"><label>Value2: </label><g:textField name="value2" value="${header4}" /></div>--}%
<br>
<div class="submit"><g:actionSubmit value="Submit" action="save"/></div>
</g:form>
</body>
And then this gsp code for the response:
<body>
<h3>API Test Results</h3>
API Tested: ${apiStart.url}, Response: ${apiStart.response3}
<br>
%{--<g:textArea name="myField" value="myValue" rows="20" cols="100"/>--}%
<div class="textarea"><label>Output</label><br><g:textArea name="myField" value="${apiStart.result3}" />
</div>
%{--Responce Code: ${apiStart.response3}<br>--}%
%{--Response: <br> ${apiStart.result3} <br>--}%
</body>
My issue: it works fine as separate pages. I want to render the results of the request on the same page as the calling request.
in the screen shot attached: I want to put the results in the text box where it says "Output Displayed here...."
I assumed templates in grails is the way to go about it. but I get a Java Null pointer exception when I try to insert the template into that part of the code.
Can someone advise and show me the best way to do this?
==================== END of Updated question ===================
thanks.
ironmantis7x
You can try using Grails templates.
Basically Template is a (reusable) part of a View.
Info:
So you create template file bookTemplate.gsp, put all the gsp/html code in there as usual (but just the part, if it will be used in the body, then don't add html, body, head tags etc.
Example:
<div class="book" id="${book?.id}">
<div>Title: ${book?.title}</div>
<div>Author: ${book?.author?.name}</div>
</div>
Then you render that template into the gsp page in places where you want them to be (with a simple grails render tag. And it will simply get compiled (as the code from template would be pasted into gsp view).
Render:
<g:render template="bookTemplate" model="[book: myBook]" />
I don't know your grails version, but on 2.4.5, and maybe on your version, you can use :
http://docs.grails.org/2.4.x/ref/Tags/submitToRemote.html
And have a look to the attribute update :
update (optional) - Either a Map containing the elements to update for
'success' or 'failure' states, or a string with the element id to
update, in which case failure events would be ignored
And you also can trigger javascript on some events, ...
In your action called in the submitToRemote button, you can render a template (but do not put your layout in this template if you render a template, otherwise you will have all you website structure rendered...) and it will be displayed in the HTML element with the ID that you have put in "update" property.
The example given in the link is interesting.

Assign an object in a form

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;
}

Query string not being passed to controller

I have what should be a relatively simple form in Rails that I'm using to send an email for two different previews, a desktop preview and a mobile preview.
<form id="email-form" role="form" action="<%= action_name == 'desktop_preview' ? email_preview_newsletter_path(#newsletter) : email_preview_newsletter_path(#newsletter, mobile: 'true') %>">
<label for="email_address">Email</label>
<input type="email" id="email_address" name="email_address" value="<%= params[:email_address] %>" placeholder="PLEASE ENTER EMAIL">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" value="Send" class="btn btn-primary"></input>
</form>
Right now I have it setup so that both previews get sent to the same endpoint, '/email_preview', but in the case of the mobile_preview I want to pass in a 'mobile' query string so that it ends up looking like this:
'/email_preview?mobile=true'
When I inspect the form on the page everything looks in order, however when it gets passed to the controller the 'mobile' part of the query string disappears and only the 'email_address' exists.
I suppose I could pass in the mobile value as a hidden field, but something about that just doesn't feel right to me. What is the best way to setup this form so that both the 'mobile' and 'email_address' key value pairs are passed as query strings when sent to the controller?
In the process of writing out this question I realized exactly what the problem was:
I had the form setup as a GET request as opposed to a POST request.
This was causing any pre-established query strings to get erased in the process of setting up the GET params being defined in the form (in this case, the 'email_address' param). Changing the form from GET to POST, (i.e. form method="POST")
Took care of this issue. Please note that if you are going to manually setup a form like this in rails then you also need to explicitly take care of the csrf token. This can be done by inserting the following input with the helper method into your form:
input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>"

asp.net mvc redirect to action and passing a parameter from user input

I have a page with a input box and a button, when the user clicks the button i want to redirect to a controller action that has as parameter the value of the input box.
<input id="CodProiect" type="text" />
<input id="Cauta" type="button" value="Cauta" onclick="window.location.href='#Url.Action("Cauta", "Componente", new { CodProiect = "param" })';"/>
How can i get the "param" from the input box ?
You could just use a form with a GET method
<form action="#Url.Action("Cauta", "Componente")" method="GET">
<input id="CodProiect" name="CodProiect" type="text" />
<input id="Cauta" type="submit" value="Cauta" />
</form>
The form will add the parameter as part of the query string of the URL e.g. www.yoursite.com/Cauta/Componente?CodProiect=user+entered+value
Value of the Action is prepared at server side and sent to the browser so you cannot have the value at the server when it is a user input.
You can use jquery to change the URL at client side.
Also passing state in an PRG scenario is a common problem in ASP NET MVC. You can either:
Store it temporarily in session
Pass it as a parameter in URL
Use a form.
Form:
<form action="Componente/Cauta">
<input id="CodProiect" type="text" />
<input id="Cauta" type="submit" value="Cauta" />
</form>
Controller:
public ActionResult Cauta(string CodProiect)
{
//Do some stuff
}
More info: http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx
Syntax may be outdated, but you get the point...

Resources