How can i get the dynamic number of textboxes values from jsp in struts? - struts-1

I am having number of textboxes, where user will enter comments in indivddual textbox. I need to fetch all the textboxes values and pass it to action class. Please help me to move forward.
This is my jsp code:
<layout:collectionItem title="Comments">
<layout:text readonly="true" property="comments"
ondblclick="javascript:enableText(this);" name="comments"
layout="false" />
</layout:collectionItem>
This is my action class code:
DynaActionForm dynaForm = (DynaActionForm) form;
TablesVo tablesVo = new TablesVo();
tablesVo.setComments((String) dynaForm.get("comments"));
System.out.println("Comments:>>>>>>>>>>>>>>>>>>>>>>>"
+ (String) dynaForm.get("comments"));
This is my struts config code:
<form-bean name="projectForm" type="org.apache.struts.action.DynaActionForm">
<action-mappings>
<action path="/Projects" type="com.rntbci.ptm.client.action.PTMManageAction"
name="projectForm" scope="session" parameter="reqCode">
<forward name="display_projects" path="tile.ptm.projects" />
<forward name="display_columns" path="tile.ptm.columns" />
</action>
</action-mappings>
I am struggling to solve this problem for the past four days.
Please do me a favour.

Give same name attribute to all your textboxes
<input type="text" name="comment"/>
<input type="text" name="comment"/>
...
<input type="text" name="comment"/>
Now in your action class instead of declaring a string variable declare a List variable
private List<String> comment; //with getter/setter
You can now iterate over this list to read the comments
Iterator<String> it = comment.iterator();
while(it.hasNext()){
System.out.println("\n comment: "+it.next());
}

Related

Liferay form does not check required fields at Add, despite checking them at Edit

I have a Liferay entity created by Service Builder, with the field "name" described as required in portlet-model-hints.xml:
<model-hints>
<model name="com.example.model.Person">
[...]
<field name="name" type="String">
<validator name="required" />
</field>
[...]
</model>
</model-hints>
Add and Edit are powered by the same JSP edit_person.jsp:
<%#include file="/html/init.jsp"%>
<%
Person person = null;
long personId = ParamUtil.getLong(request, "personId");
if (personId > 0) person = PersonLocalServiceUtil.getPerson(personId);
%>
<aui:model-context bean="<%= person %>" model="<%= Person.class %>" />
<portlet:renderURL var="viewPersonURL" />
<portlet:actionURL name='<%= person == null ? "addPerson" : "updatePerson" %>'
var="editPersonURL" windowState="normal" />
<aui:form action="<%= editPersonURL %>" method="POST" name="fm">
<aui:fieldset>
<aui:input type="hidden" name="personId"
value='<%= person == null ? "" : person.getPersonId() %>'/>
<aui:input name="name" />
</aui:fieldset>
<aui:button-row><aui:button type="submit" /></aui:button-row>
</aui:form>
PROBLEM: When adding a new person, no validation is done, I can enter no name and push submit and the entity is saved with an empty name:
Despite the fact that when editing that person, the name requirement is enforced:
This happens on Firefox but not on Chrome.
This is a bug in Liferay 6.2:
https://issues.liferay.com/browse/LPS-48087
This bug has been fixed in Liferay 7.0.0 M2

CFWheels: Form Helper Radio Button

I am using CFWheels for form validation. I have presenseOf() validation checks in both objects models. I have a form with a textbox and a set of radio buttons.
However If I submit the form empty, the validation for supervisor works but validation for the user checklist does not work. It gives the error;
"uchecklist" is not defined in the params variable.
On further observation, I notice that when the form is submitted, params struct has the "supervisor[name]" object but its empty, however it doesn't even have the "uchecklist[cstatus]" object. Moreover only when I select one of the radio buttons then the "uchecklist[cstatus]" object is submitted with that radio button's value.
I need to validate if at least one of the radio button is select, I guest this functionality is different from the empty text box validation.
Can someone show me how a radio button is validated using CFWheels form helpers.
Controller
public function t_validate()
{
title = "Home";
supervisor = model("supervisors");
uchecklist = model("user_checklist");
}
public function t_validate_complete()
{
title = "Home";
supervisor = model("supervisors").new(params.supervisor);
supervisor.save();
uchecklist = model("user_checklist").new(params.uchecklist);
uchecklist.save();
renderPage(action="t_validate");
}
View
<cfoutput>
<cfdump var="#params#">
#errorMessagesFor("supervisor")#
#startFormTag(action="t_validate_complete")#
<div>
<label for="">Supervisor:</label>
<input name="supervisor[name]" value="" />
</div>
<fieldset>
<input type="radio" name="uchecklist[cstatus]" value="1" />
<label for="profile-eyeColorId-2">Blue</label><br />
<input type="radio" name="uchecklist[cstatus]" value="2" />
<label for="profile-eyeColorId-1">Brown</label><br />
<input type="radio" name="uchecklist[cstatus]" value="3" />
<label for="profile-eyeColorId-3">Hazel</label><br />
</fieldset>
<div>
<input type="submit" value="Save Changes" />
</div>
#endFormTag()#
</cfoutput>
An unchecked radio button will submit no data to the server. This isn't a unique problem to ColdFusion or CFWheels.
To fix, provide a default value for the struct at the beginning of your controller action:
public function t_validate_complete()
{
// Provides an empty struct for the model to consume if none of the radio buttons are checked.
param name="params.uchecklist" type="struct" default="#StructNew()#";
title = "Home";
supervisor = model("supervisors").new(params.supervisor);
supervisor.save();
uchecklist = model("user_checklist").new(params.uchecklist);
uchecklist.save();
renderPage(action="t_validate");
}

Spring WebFlow: view-state is not calling validation method before <evaluate> tag

This problem is driving me crazy.
I have following view-state:
<on-start>
<evaluate expression="new com.zxxztech.zecure.services.webflow.FormularioConfirmacionCorreo()"
result="flowScope.ccForm" />
</on-start>
<view-state id="activacionManual" model="ccForm" >
<transition on="enviar" to="resultado" bind="true">
<evaluate expression="usersManager.activarUsuario(ccForm.correo, ccForm.codigo)"
result="flowScope.resultado" />
</transition>
<transition on="cancelar" to="cancelar" validate="false" bind="false" />
</view-state>
And this is this the Validation class:
#Component
public class FormularioConfirmacionCorreoValidator {
#Autowired
private UsersManager usersManager;
public void validateActivacionManual(FormularioConfirmacionCorreo ccForm, ValidationContext validContext) {
...
[Validation logic]
}
public UsersManager getUsersManager() {
return usersManager;
}
public void setUsersManager(UsersManager usersManager) {
this.usersManager = usersManager;
}
}
When form is submited, webflow execute <evaluate> tag directly, without calling validation method.
I don't know what could I doing wrong.
Edit:
This is the activacionManual.jsp file:
...
<form:form cssClass="ym-form" modelAttribute="ccf" method="post" action="${flowExecutionUrl}">
<form:errors cssClass="ym-error" element="div" path="*"/>
<div class="ym-box">
<div class="ym-fbox">
<label for="correo"><spring:message
code="activacion.form.correo.label"
text="activacion.form.correo.label" /></label>
<form:input path="correo" />
</div>
<div class="ym-fbox">
<label for="codigo"><spring:message
code="activacion.form.codigo.label"
text="activacion.form.codigo.label" /></label>
<form:input path="codigo" />
</div>
<div class="ym-fbox-footer ym-fbox-button">
<input class="ym-button ym-gr" type="submit"
value="<spring:message code="formulario.button.cancelar" text="formulario.button.cancelar" />"
name="_eventId_cancelar">
<input class="ym-button ym-primary ym-gr" type="submit"
value="<spring:message code="formulario.button.enviar" text="formulario.button.enviar" />"
name="_eventId_enviar">
</div>
</div>
</form:form>
...
The second way is to define a separate object, called a Validator, which validates your model object. To do this, first create a class whose name has the pattern ${model}Validator, where ${model} is the capitialized form of the model expression, such as booking. Then define a public method with the name validate${state}, where ${state} is the id of your view-state, such as enterBookingDetails.
Thus, since your model attribute is ccForm, the validator Class must be named CcFormValidator. (Or rename your model attribute.)
(Also, I think your JSP is going to have problems using modelAttribute="ccf" instead of "ccForm". The model name needs to match across flow.xml, JSPs, and validators.)

binding to list property of an object returns nothing mvc3

Context: ASP MVC 3/4, VB.net
I am trying to bind to an object that has a list property of complex type.
Problem statement: upon post back I get values in all the properties other than the complex type property, it is returned as nothing. I am doing something wrong because of which default model binder is not able to bind my property which is a list of complex type.
What am i doing wrong?
My View Model classes:
Public Class Customer
Public Property ID As Integer
Public Property FirstName As String
Public Property LastName As String
Public Appointments As IList(Of Appointment)
End Class
Public Class Appointment
Public Property ClientName As String
Public Property [Date] As DateTime
Public Property TermsAccepted As Boolean
End Class
My action methods in controller look like this
Function CreateCusotmerWithMultipleBookings() As ActionResult
Dim Modeldata As New Customer With {.ID = 1, .FirstName = "First Name", .LastName = "Last Name"}
Modeldata.Appointments = New List(Of Appointment) From {New Appointment, New Appointment, New Appointment}
Return View(Modeldata)
End Function
<HttpPost()> _
Function CreateCusotmerWithMultipleBookings(FormData As Customer) As ActionResult
Return View(FormData)
End Function
My view looks like this:
#ModelType Customer
#Using Html.BeginForm
#Html.EditorForModel
If Model.Appointments IsNot Nothing AndAlso Model.Appointments.Count > 0 Then
For i As Integer = 0 To Model.Appointments.Count - 1
#:<b >Appointment #i</b><br />
#Html.TextBoxFor(Function(x) x.Appointments(i).ClientName) #:<br />
#Html.TextBoxFor(Function(x) x.Appointments(i).Date) #:<br />
#Html.TextBoxFor(Function(x) x.Appointments(i).TermsAccepted)#:<br />
Next
End If
End Using
HTML that gets generated from this view is something like: (I have removed unnecessary mark up to ease reading)
<body>
<form action="/testarea/Appointment/CreateCusotmerWithMultipleBookings" method="post">
<input id="ID" name="ID" type="number" value="1" />
<input class="text-box single-line" id="FirstName" name="FirstName" type="text" value="First Name" />
<input class="text-box single-line" id="LastName" name="LastName" type="text" value="Last Name" />
<input id="Appointments_0__ClientName" name="Appointments[0].ClientName" type="text" value="" />
<input id="Appointments_0__Date" name="Appointments[0].Date" type="text" value="1/1/0001 12:00:00 AM" />
<input id="Appointments_0__TermsAccepted" name="Appointments[0].TermsAccepted" type="text" value="False" />
<input id="Appointments_1__ClientName" name="Appointments[1].ClientName" type="text" value="" />
<input id="Appointments_1__Date" name="Appointments[1].Date" type="text" value="1/1/0001 12:00:00 AM" />
<input id="Appointments_1__TermsAccepted" name="Appointments[1].TermsAccepted" type="text" value="False" />
<input id="Appointments_2__ClientName" name="Appointments[2].ClientName" type="text" value="" />
<input id="Appointments_2__Date" name="Appointments[2].Date" type="text" value="1/1/0001 12:00:00 AM" />
<input id="Appointments_2__TermsAccepted" name="Appointments[2].TermsAccepted" type="text" value="False" />
<input type="submit" value="Create customer with multiple appointments" />
</form>
Question again:
Why does the formdata.Appointments in following controller has nothing value in it?
<HttpPost()> _
Function CreateCusotmerWithMultipleBookings(FormData As Customer) As ActionResult
Return View(FormData)
End Function

Struts2 AJAX validation doesn't stay on page

I've been trying for a few days now to make Struts2 AJAX validation work but I can't solve one last problem. I'm using the struts2jquery plugin to asynchronously submit my form:
<div id="result"></div>
<s:form action="RegisterUser" theme="xhtml" method="post">
<s:textfield key="firstname" label="First name" size="35"
required="true" />
<s:textfield key="lastname" label="Last name" size="35"
required="true" />
<s:textfield key="address" label="Address" size="35"
required="true" />
<s:textfield key="phone" label="Phone number" size="35" />
<s:textfield key="username" label="Username" size="35"
required="true" />
<s:password key="password" label="Password" size="35"
required="true" />
<s:textfield key="email" label="E-mail address" size="35"
required="true" />
<sj:submit key="Inregistrare" targets="result" align="right"
button="true" validate="true" onSuccessTopics="notifyRegistration" />
</s:form>
I've included the required scripts:
<script type="text/javascript" src="./js/registerScript.js"></script>
<!-- This files are needed for AJAX Validation of XHTML Forms -->
<script src="${pageContext.request.contextPath}/struts/utils.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/struts/xhtml/validation.js"
type="text/javascript"></script>
and the tag:
<sj:head jqueryui="true" />
The onSuccess handler:
$(document).ready(function(){
$.subscribe('notifyRegistration', function(event,data) {
var registrationStatus = event.originalEvent.data.registrationStatus;
if(registrationStatus == 'SUCCESS'){
alert('Contul dumneavoastra a fost creat cu success!');
window.location.href = "./index.html";
} else {
alert('Contul dumneavoastra nu a putut fi creat. Va rugam incercati din nou.');
}
});
});
My configuration looks like this:
<action name="RegisterUser" class="actions.Register" method="execute">
<interceptor-ref name="jsonValidationWorkflowStack"/>
<result name="input">/pages/Register.jsp</result>
<result type="json"/>
</action>
And the execute method of my action class:
public String execute() throws Exception {
if (isInvalid(getUsername()) || isInvalid(getPassword())
|| isInvalid(getEmail())) {
registrationStatus = REGISTRATION_ERROR;
}
if (registerUser()) {
registrationStatus = REGISTRATION_SUCCESS;
return SUCCESS;
}else {
registrationStatus = REGISTRATION_ERROR;
}
return SUCCESS;
}
The registerUser() method makes the actual insert into the database. The validation XML is called Register-Validation.xml.
The validation works fine - if some fields are not filled in, it shows the error labels without refreshing the page. My problem is that even is the action returns SUCCESS or ERROR, the browser displays the JSON that it sent back on another page, ../Register.action. I have no idea why it doesn't enter my onSuccess handler. I've successfully used AJAX on other forms, the only difference here is that I use the validation xml and the jsonValidationWorkflowStack interceptor. Why is this happening and how can I avoid being redirected? Why doesn't the request reach the onSuccess handler?
Do you have getters for registrationStatus in your Action ?
I would put an alert(event.originalEvent.data.registrationStatus); in your notifyRegistration callback function, just to see what is its value.
By the way, it seems that you have mixed
Struts2-jQuery Plugin AJAX Form Validation with Struts2 XHTML Theme
with
Struts2-jQuery Plugin: Remote Link that handle an JSON Result with an onSuccessTopic
AFAIK (but I've never used this specific kind of validation), the validation should not be handled in execute(), but in validate() or through XML, or with Annotations.
The example in Struts2-jQuery Plugin showcase uses Annotations, but you can easily transform it in XML and try the showcase.
You would have no need to use the javascript function nor the onSuccessTopic at all, following the example.
You can run it in the showcase too, under Forms -> Forms with Validation (but stick to the documentation for the code, because the code in the showcase seems to miss some pieces... for example the validation against "test" password).

Resources