I have a liferay portlet with a simple form for entering two numbers and submitting them to be added:
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%# taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<portlet:defineObjects />
<portlet:actionURL var="calculateURL">
<portlet:param name="mvcPath" value="/html/calculator/edit.jsp" />
</portlet:actionURL>
<aui:form action="<%= calculateURL %>" method="post">
<aui:input label="x" name="x" type="text" value="${x}"/>
<aui:input label="y" name="y" type="text" value="${y}"/>
<aui:button type="submit" value="add"/>
</aui:form>
This works fine. I would now like to add a button that allowed me to subtract the numbers instead. But when I add the new button, I don't know how to differentiate between which button was pressed, when I am in my processAction method. How can I do this?
Alternatively: I have found this answer on how to do it, but I wasn't able to get it to work. Does it point me in the right direction, and should I keep experimenting with the answer given there?
You can have two different action method in your controller class and in jsp based on which button clicked, call the action url accordingly. Find below code which changes form action based on the button clicked. This helps you keep your business on logic seperate in your controller class. Else you can have only action and then pass parameter to action to identify what to perfrom (add or subtract)
<portlet:actionURL var="subtractNumberURL">
</portlet:actionURL>
<portlet:actionURL var="addNumberURL">
<portlet:param name="mvcPath" value="/html/calculator/edit.jsp" />
</portlet:actionURL>
<script type="text/javascript" charset="utf-8">
function submitForm(action){
if(action==0){
A.one('<portlet:namespace/>form').set('action',"<%=addNumberURL%>");
}else{
A.one('<portlet:namespace/>form').set('action',"<%=subtractNumberURL%>");
}
}
</script>
<aui:form action="<%= addNumberURL%>" name="form" method="post">
<aui:input label="x" name="x" type="text" value="${x}"/>
<aui:input label="y" name="y" type="text" value="${y}"/>
<aui:button type="submit" value="add" onClick="submitForm(0)"/>
<aui:button type="submit" value="subtract" onClick="submitForm(1)"/>
</aui:form>
I've successfully implemented this way (tested on liferay 6.1.2 and FF).
I've found this article very useful!
Keep into account function name: must NOT be "submitForm"!
<aui:script use="aui-base">
Liferay.provide(window, 'mysubmitForm', function(action) {
if(action=='add'){
A.one('#<portlet:namespace/>form').set('action','<%=addNumberURL.toString()%>');
}else{
A.one('#<portlet:namespace/>form').set('action','<%=subtractNumberURL.toString()%>');
}
});
</aui:script>
Personally I prefer a clean and simple solution into javascript with just one input hidden on the HTML code and then in the action with a switch select the correct code to be executed.
I use Jquery but the code can be implemented on plain javascript as well:
Inside the form, we put a hidden variable like this:
<aui:input name="botonClicked" id="botonClicked" type="hidden"></aui:input>
We define then our buttons but with "type='button'", not with "type='submit'", for example:
<aui:button icon="icon-save" iconAlign="left" value="Save" type="button" cssClass="btn-primary buttonListener" name="Save"></aui:button>
<aui:button icon="icon-save" iconAlign="left" value="Send" type="button" cssClass="btn-primary buttonListener" name="Send"></aui:button>
And then with a simple jquery we put the button clicked on our hidden input and submit the form:
$(".buttonListener").click(function(){
var nombre = $(this).attr("name");
nombre = nombre.replace(namespace,'');
$("#botonClicked").val(nombre);
$("#OurForm").submit();
});
In your Java code, in the Action code, just we use a switch to know wich button was pressed and call our different functions:
String botonClicked= ParamUtil.getString(actionRequest, "botonClicked");
switch (botonClicked) {
case "Save":
Guardar(actionRequest, actionResponse);
break;
case "Send":
Enviar(actionRequest, actionResponse);
break;
default:
break;
}
For me at least this solution is cleaner and it works perfectly.
Related
I'm making a form to add events to a list but I need to be able to see in that form the previous events from that list. I have a jsp that shows a list of events but it takes an attribute usually added by the controller when you access the list directly from the browser.
So how can I add the list jsp filling that attribute so it shows a list and not just the headers?
I have alreay included the jsp using
<jsp:include page="comp_list.jsp"></jsp:include>
And it shows the headers but as there is no attribute it shows no list. I tried adding attributes to the include like:
<jsp:include page="comp_list.jsp">
<jsp:attribute name="compensaciones">
${compensaciones}
</jsp:attribute>
</jsp:include>
But when I do it it shows an error telling me that this cannot be done.
Also tried params but that would not be the answer for me because params are treated in the controller and not in the jsp itself.
I'm just getting the header of the list which is fine, but i would like to see the list.
Edit: this is how i build the list in case you are wondering
<tbody>
<c:forEach var="comp" items="${compensaciones}">
<td>${comp.getSomething()}</td>
...
</c:forEach>
</tbody>
<jsp:include page="pagename.jsp" />
i thing you are not provide extension in your include tag
Sometimes since I've had prior experience back in the days with HTML and PHP, we simply just would include things like navigation and header for easier management.
I'm unsure for what purpose you're including JSP, but here's an example of how I've done it since I include JSP if a boolean is true.
The site that is accessed:
<div class="row">
<div class="col-lg-2">
</div>
<div class="col-lg-8">
<%
if (loggedin) {
%>
<%# include file="includes/profile.jsp" %>
<% } else {
out.println("<div><h2>You aren't logged in!</h2></div>");
}
%>
</div>
<div class="col-lg-2">
</div>
</div>
And the top and bottom of the JSP file I'm including doesn't contain things like head, title, html, body etc.
<%
User currUser = null;
currUser = (User) session.getAttribute("user");
%>
<div>
<h2>Du er logget ind, velkommen <% out.println(currUser.getUsername().toUpperCase()); %></h2> <br>
<h5>Din Saldo: <b><% if (currUser.getBalance() < 0) { out.println("<font color='red'>" + currUser.getBalance() + "</font>");} else { out.println("<font color='green'>" + currUser.getBalance() + "</font>");} %></b></h5>
<br>
<form class="form" method="post" action="#">
<h4>Oplysninger: </h4>
<h6>
For at ændre oplysninger skal du indtaste dit kodeord!
</h6>
Nuværende Kode: <input type="password" class="form-control" placeholder="kodeord" name="password" required>
<hr>
Email: <input type="text" class="form-control" value="<% out.println(currUser.getEmail()); %>" name="email"> <br>
Brugernavn: <input type="text" class="form-control" value="<% out.println(currUser.getUsername()); %>" name="username"> <br>
<input type="submit" class="btn btn-default" value="Indsend Oplysninger" />
</form>
</div>
When importing JSP into JSP, it's important to know that they will conflict if 1. Duplicate Local Variables. 2. Certain HTML tags aren't correct.
Your intended use seems very complicated to me since I'm not quite understanding it, sorry :3 but if you can't get it working consider to throw it to a session and if it's a one time use then remove it once you used it.
This is working from dacades
<%# include file="../scripts/standard_head_declaration.jsp" %>
Good Morning all. I have an issue that I am trying to solve but I am stuck, partially due to me not having a full understanding of JSP/ Java platform, and not having a full understanding of what/ how to implement my code in the right way. I do have an ASP background, so I am a bit familiar with some concepts.
The issue I am running into is: I am trying to populate a dynamic label and text box to appear on a webpage (JSP). I have successfully been able to populate the textboxes with a piece of JavaScript code, however, when I submit the form (on Postback) my dynamic controls are gone but all of my static controls are still present. I need to find a way to keep my information in the dynamic control on submit as well. The form does not submit when I have errors but when the form finish rendering all information and dynamic text are all lost.
My Solution: I have decided to use hidden fields to hold this information but I am unable to fire off the hidden fields after form submit: Please have a look below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript">
function validateForm(){
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="" && document.getElementById('two').value==1){
alert("EMPTY");
document.getElementById('text').style.display = "block";
return false;
}else{
document.myform.submit();
}
}
function display(el) {
if (el.value == "two") {
document.getElementById('text').style.display = "block";
}else {
document.getElementById('text').style.display = "none";
document.getElementById('dynbox').value = '';
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
<label >First Name</label> <input type="text"/>
<div>
<input type="radio" name="radio1" id="one" value="one" onchange="display(this);"/>Eligible
</div>
<div>
<input type="radio" name="radio2" id="two" value="two" onchange="display(this);"/>Not Eligible
</div>
<div id="text" class="glassy" name="mytext" style="display:none;">Other: <input type="text" id="dynbox"/>
</div>
<div>
<input type="hidden" name="mytext" value="${mytext}" />
<br></br>
<input type="submit" onclick="validateForm()" value="Submit"/>
</div>
</form>
</body>
</html>
What I am trying to do is select the "Not Eligible" option and type some text in the text box 'mytext' then press submit. Once I press submit, and if the First Name textbox is not filled in, then I want to trigger my hidden textbox so that I won't loose my information in my dynamically created textbox.
I hope this makes sense. I am not sure of how to do in JSP. Can someone give guidance on how to get my expected results? Keeping dynamic controls after Postback?
Thanks in advance.
One thing first: don't let the names Java and Java-Script confuse you. They have (almost) nothing in common. What you are using here is Java-Script only (no Java, no JSP anywhere).
Anyway, I think it is the condition in your validateForm() function that does not work.
I tested it a little bit and it works with these changes:
your form
<form name="myForm" action="test.html" method="get" onsubmit="return validateForm();">
<label >First Name</label> <input type="text" id="firstName"/>
<div>
<input type="radio" name="radio1" id="one" value="one" onchange="display(this);"/>Eligible
</div>
<div>
<input type="radio" name="radio2" id="two" value="two" onchange="display(this);"/>Not Eligible
</div>
<div id="text" class="glassy" name="mytext" style="display:none;">Other: <input type="text" id="dynbox"/>
</div>
<div>
<input type="hidden" name="mytext" value="${mytext}" />
<br></br>
<input type="submit" value="Submit"/>
</div>
</form>
I simply changed the first input and gave it an ID (since I couldn't find the id 'fname' anywhere), so we can access it with JavaScript.
The next thing is your submit button. You had an additional onclick="validateForm()"; there – which indeed calls the validateForm function but does not listen to the returned value (it executes the function.. nothing more). So the onsubmit="return validateForm()" is enough.
your validate function
function validateForm() {
var x = document.getElementById('firstName').value;
if ((x == null || x == "")) {
alert("EMPTY");
// document.getElementById('text').style.display = "block";
return false;
} else {
return true;
}
}
x can now be retrieved by the element's id (which I find easier).. Anyway, the if condition was one of the problems. In your form you set the value of your radio button 'two' to two. But in the if condition you ask if could be 1... which (in my understanding) should never happen. I just removed it to show you that your function works like this. If you want to check the state of the second radio button, you can test it like this:
if(document.getElementById('two').checked == true)
or even better
if(document.getElementById('two').checked)
one last thing: in your else statement, you can simply return true instead of calling submit.. because here:
onsubmit="return validateForm();"
you ask your validateForm() function to give you either true and then submit or false and then stop submitting.
Oh, one last thing (it'S the last, promise): Java and Java-Script handle all && and || in the order: first ´x==null´ would be tested and then x=="" && document.getElementById('two').value==1 would be evaluated together (&& has a stronger binding than ||).. Just for your information :)
I am trying to figure out the best way to dynamically change some page html on my page using ajax and struts2. I have these tag files containing the jsp of the html that needs to be changed. I want to use these tag files for the ajax calls and not have to copy the html from them into some other source and worry about populating the data into that html, because the JSP already handles that.
So what I am doing is making a Jquery Ajax call to a jsp that simply includes the tag file I want the updated html for, and in that tag file, I am making a call to the struts2 action with the <s:action /> tag. What I want, and what I think would be proper is if I could have that action execute, and all the struts2 jsp tags below would use the data from that action class that was executed. So for example, if I have <s:fielderror /> tags latter on in the jsp, the field errors that were added in the action that was executed with the action tag, would be rendered in the same jsp by this fielderror tag. Here is an example of what I am trying to do.
tag file in question:
<%# tag language="java" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<%-- This is the action that I want to execute and use for the rest of the jsp in this file --%>
<s:action name="ajaxRegister" namespace="/actions" />
<form id="register_form" action="register/" method="post">
<c:choose>
<c:when test="${not empty sessionScope.username}">
<div class="inputs">
<h1>Create Your Password</h1>
<label style="padding-bottom: 10px;">Create your password to finish your registration</label>
<label for="password1">Password:</label>
<input type="password" name="password1" id="register_pwd_1" data-enter-click="finish_button" />
<label for="password2">Verify Password:</label>
<input type="password" name="password2" id="register_pwd_2" data-enter-click="finish_button" />
<input name="noScript" type="hidden" value="${pageContext.request.servletPath}" data-no-script />
<div id="register_error" class="response">
<s:fielderror fieldName="register.error" />
</div>
<div class="clear"></div>
</div>
<input type="submit" id="finish_button" value="Finish" />
</c:when>
<c:otherwise>
<div class="inputs">
<h1>Not a member yet? Sign Up!</h1>
<input name="uuid" type="text" data-no-script />
<div id="paste_input"></div>
<input name="noScript" type="hidden" value="${pageContext.request.servletPath}" data-no-script />
<div id="register_error" class="response">
<s:fielderror fieldName="register.error" />
</div>
</div>
<input type="submit" id="register_button" value="Register" />
</c:otherwise>
</c:choose>
</form>
My problem is that even though the first thing I do in this jsp is calling the action, the fielderror tags do not populate the html with the field errors that are generated in the action class. Is this possible to do? Also, I have not been able to figure out how to pass parameters as the properties to be set in the action class. The parameters that the action class needs to use are the values of that registration form that the user submits. It is that submit button that calls this jsp to render a response for them. But if I cannot get those form values to the action, then there is no point.
Also, I am not using json for this because if the register process is completed, then a totally new part of the page needs to be dynamically added, so its not just simple error messages that I am returning to the user. And I do not want to have the html in strings in the java code, or javascript, or even somewhere else, because I already have it in the JSP.
Do I have the right idea?
I'm trying to retrieve a post value from a hook on the same page so when i value is right, content will appear.
I added this code in the hook to have it on the specified page.
<portlet:actionURL secure="<%= PropsValues.COMPANY_SECURITY_AUTH_REQUIRES_HTTPS || request.isSecure() %>" var="SecondloginURL">
<portlet:param name="saveLastPath" value="0" />
<portlet:param name="struts_action" value="/journal_content/view" />
</portlet:actionURL>
<aui:form action="" name="auth" method="POST">
<aui:input label="Second Password" type="password" name="password" />
<aui:button type="submit" value="authenticate" />
</aui:form>
I managed to retrieve the value but when it's validated session started but it doesn't move cross-pages.
Here is the code:
<% String pass = request.getParameter("password"); %>
<c:if test="<%= pass.equals(\"1234\") %>">
<%
HttpSession session1 = request.getSession();
session1.setAttribute("pass","authenticated");
String foo = (String) session1.getAttribute("pass");
out.println(foo);
%>
<h2>this is the second password and it's working</h2>
<div class="journal-content-article" id="article_<%= articleDisplay.getCompanyId() %>_<%= articleDisplay.getGroupId() %>_<%= articleDisplay.getArticleId() %>_<%= articleDisplay.getVersion() %>">
<%= RuntimePortletUtil.processXML(application, request, response, renderRequest, renderResponse, articleDisplay.getContent()) %>
</div>
</c:if>
In a Liferay hook you can override stock Liferay jsps, thus also add forms.
You can also override Liferay Actions and other Liferay classes. You don't make clear where you put the above code and what else you have in your hook, neither what you are trying to achieve.
First: You should direct your form to some <portlet:actionURL/> and then, depending on the portlet this jsp is invoked from, you'll have to implement or override the action handler for that portlet. In there you'll be able to get the parameter value from the ActionRequest
I'm using JSP and jQuery Autocomplete UI.
I'm trying to pass the 'value' of the selected element in my autocomplete box into a form as a hidden value on my JSP.
Here is my script:
<script>
$(function() {
$("#search").autocomplete({
source: "list.jsp",
dataType: "json",
select: function (event, ui) {
$("#userId").val(ui.item.value);
return false;
}
});
});
</script>
Here is my form:
<form method="GET" action="view">
<div class="autocomplete">
<p>Search: <input id="search"></p>
</div>
<input type="hidden" name="userId" value="<%request.getParameter("userId");%>"/>
</form>
The autocomplete box works great but I can't seem to get a handle on the select element id!
Any help would be greatly appreciated... thanks in advance!
Use the following code to set the value of the hidden variable
// use <%= %>
<input type="hidden" name="userId" value="<%=request.getParameter("userId")%>"/>
You have used a scriptlet directly. Probably that is what is causing the problem.
Ok, I have solved the issue now.
I should have been using #userId as follows...
<input type="hidden" name="userId" id="userId" />
Where id="userId" references the #userId.