Getting null value from struts/dojo datetimepicker in my struts 2 action? - struts2

I am using two struts/dojo datetimepicker in jsp page of my struts 2 web application. These allow to select date and displaying properly but when i submit the form and access the datetimepickers value in variables(with getter and setter) with same name as name of datetimepicker in jsp form it returns null value.
i want how to get datetimepickers value in struts action and then store them in MySQL database
my jsp page-->
<%#taglib prefix="sx" uri="/struts-dojo-tags"%>
<html>
<head>
<sx:head />
</head>
<body>
<form name="cFrom" method="post" action="saveForm"
enctype="multipart/form-data">
state Date: <sx:datetimepicker formatLength="medium" value="%{'today'}"
name="sDate"></sx:datetimepicker><br/>
End Date: <sx:datetimepicker formatLength="medium" name="eDate">
</sx:datetimepicker><br/>
<button type="submit">Save</button>
</form>
</body>
</html>
action class-->
import java.util.*;
public class saveFormAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private Date sDate;
private Date eDate;
public Date getsDate() {
return sDate;
}
public void setsDate(Date sDate) {
this.sDate = sDate;
}
public Date geteDate() {
return eDate;
}
public void seteDate(Date eDate) {
this.eDate = eDate;
}
public String saveForm() throws SQLException{
Connection con=DBConnect.makeConnection();
PreparedStatement pst=con.prepareStatement("INSERT INTO saveForm(Start_ON,
Expire_On) values(?,?)");
pst.setDate(1, sDate);
pst.setDate(2, eDate);
int i=0;
i=pst.executeUpdate();
if(i>0){
return SUCCESS;
}
return ERROR;
}
}
MySQL table-->
CREATE TABLE saveform(start_on DATE, Expire_On DATE)

Datetimepicker is giving you value in format of 2013-03-27T00:00:00+11:00 when your you use private String Date but you are using private Date sDate which is causing problem
of type missmacth . TO resolve this problem need to do type conversion from datetimepicker to java.util.Date format you can do it by this way
String obj = "2013-03-27T00:00:00+11:00";
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
try {
SimpleDateFormat parseFormatter = new SimpleDateFormat("yyyy-MM-dd");
//SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss+hh:mm");
Date date = parseFormatter.parse(obj);
String formattedDate = formatter.format(date);
System.out.println(formattedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

I corrected my getter and setter and I had another error in the following lines-->
pst.setDate(1, sDate);
pst.setDate(2, eDate);
I replaced above lines of code with the following -->
pst.setDate(1, new java.sql.Date(sDate.getTime()));
pst.setDate(2, new java.sql.Date(eDate.getTime()));

Related

ASP.NET MVC 4 Custom Validation not working

I am trying to use a custom validation but its been ignored. I do not get any errors or anything. It simply does nothing. What am i doing wrong? Thank you for reading.
---ModelMetadata.cs----
using System.ComponentModel.DataAnnotations;
using myproject.Common;
namespace myproject.Models
{
[MetadataType(typeof(ModelMetaData))]
public partial class Reference
{
}
public class ModelMetaData {
[Required]
[Display(Name = "Full Name *")]
[ExcludeCharacters("/.,!##$%")] // <<<====== This is being ignored.
public string Name { get; set; }
}
}
--Create.cshtml ----
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
#using (Html.BeginForm()){
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="editor-field">
#Html.EditorFor(model => model.Name) // <<<====== field
#Html.ValidationMessageFor(model => model.Name)
</div>
--ExcludeCharacters.cs ---
namespace myproject.Common
{
public class ExcludeCharacters : ValidationAttribute
{
private readonly string _chars;
public ExcludeCharacters(string chars) : base("{0} contains invalid characters")
{
_chars = chars;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
for (int i = 0; i < _chars.Length; i++)
{
var valueAsString = value.ToString();
if (valueAsString.Contains(_chars[i].ToString()))
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
}
return ValidationResult.Success;
}
}
}
Please check the action method in your controller - make sure the model type is used by a parameter, e.g.
public ActionResult Foo(ModelMetaData model)
i had exactly same problem, and was using same codes as well. i simply shutdown my application and restarted again. it worked for me. try this
Your code generally looks about right. This would validate, however, at the server side, the way you generally have it and if it was working. Moreover, I'm unsure of why some examples are only overriding the ValidationResult version of the IsValid method, and yet other examples are only overriding the bool variant.
If you want client side validation, you need to implement IClientValidatable , and register the adapter on the client side.
Below is some code I was able to make work. I needed to include my js file after my validation inclusion, and since I was using DevExpress with include client libraries, I needed to run it after them as well.
You'll also (for client side to work), want to use EditorFor or TextBoxFor type methods to add the fields, but this appears to be something you are already doing. Do, however, check your html and look for said validation proprieties being added.
I've tested this with my MM/dd/yyyy fields.
RangeSmallDateTime.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace YourNamespaceHere.Filters
{
public class RangeSmallDateTime : ValidationAttribute, IClientValidatable
{
private static DateTime _minValue = new DateTime(1900, 1, 1);
private static DateTime _maxValue = new DateTime(2079, 6, 6);
public override bool IsValid(object value)
{
DateTime? dateValue = value as DateTime?;
if (!dateValue.HasValue)
{
return true;
}
else
{
return (dateValue.Value >= _minValue && dateValue.Value <= _maxValue);
}
}
public override string FormatErrorMessage(string name)
{
return string.Format("The '{0}' field has an invalid value.", name);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "rangesdt";
yield return rule;
}
}
}
SmallDateTimeValidator.js:
$.validator.unobtrusive.adapters.addBool("rangesdt");
$.validator.addMethod("rangesdt", function (value, element) {
if (value == null) {
return true;
}
var date = new Date(value); // MM/dd/yyyy
var minDate = new Date(1900,1,1);
var maxDate = new Date(2079, 6, 6);
if (!dates.inRange(date, minDate, maxDate))
return false;
return true;
});
// Source: http://stackoverflow.com/questions/497790
var dates = {
convert: function (d) {
// Converts the date in d to a date-object. The input can be:
// a date object: returned without modification
// an array : Interpreted as [year,month,day]. NOTE: month is 0-11.
// a number : Interpreted as number of milliseconds
// since 1 Jan 1970 (a timestamp)
// a string : Any format supported by the javascript engine, like
// "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
// an object : Interpreted as an object with year, month and date
// attributes. **NOTE** month is 0-11.
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[0], d[1], d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year, d.month, d.date) :
NaN
);
},
compare: function (a, b) {
// Compare two dates (could be of any type supported by the convert
// function above) and returns:
// -1 : if a < b
// 0 : if a = b
// 1 : if a > b
// NaN : if a or b is an illegal date
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(a = this.convert(a).valueOf()) &&
isFinite(b = this.convert(b).valueOf()) ?
(a > b) - (a < b) :
NaN
);
},
inRange: function (d, start, end) {
// Checks if date in d is between dates in start and end.
// Returns a boolean or NaN:
// true : if d is between start and end (inclusive)
// false : if d is before start or after end
// NaN : if one or more of the dates is illegal.
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(d = this.convert(d).valueOf()) &&
isFinite(start = this.convert(start).valueOf()) &&
isFinite(end = this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
}

Do not propagate conversation manually +CDI +JS2 +WELD

I have a xhtml with a form with a backing bean running in ConversationScoped.
I want create a FORM that submits and do not propagate the conversation (CID).
On the generated html the CID appears in the action on the form tag:
<form id="forme" name="form_nova_senha" method="post" action="/plma/index.xhtml?cid=1" enctype="application/x-www-form-urlencoded">
I found reading source of WeldPhaseListener
public static String getConversationId(FacesContext facesContext, ConversationContext conversationContext) {
Map<String, String> map = facesContext.getExternalContext().getRequestParameterMap();
if (map.containsKey(NO_CID))
return null; // ignore cid; WELD-919
String cidName = conversationContext.getParameterName();
String cid = map.get(cidName);
log.trace(FOUND_CONVERSATION_FROM_REQUEST, cid);
return cid;
}
Just need to put the nocid paramenter on request.

How to pass JSF variable to jQuery

Suppose i have JSF page
<h:body>
<h:form id="formID" prependId="false">
<h:outputText id="randomID" value="#{randomNumber.random}"/>
<h:commandButton id="buttonID"
value="Random"
onclick="myArrayList(countries)" /> //just example
</h:form>
</h:body>
#ViewScoped
public class RandomNumber {
private int totalCountries;
private String data = "Afghanistan, Albania, Zimbabwe";
private List<String> countries;
public RandomNumber() {
countries = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(data, ",");
while(st.hasMoreTokens()) {
countries.add(st.nextToken().trim());
}
totalCountries = countries.size();
} //end of constructor
} //end of class RandomNumber
.js file
function myArrayList(countries) {
.....
}
See when user click on button then i want to call Jquery function whom i am passing my ArrayList. Is it possible to pass your current JSF variable with values to javascript or jQuery?
Thanks
EDIT
**_________________________________________________-*
<h:body>
<h:form id="formID" prependId="false">
<h:outputText id="countries" value="#{countries.countries}" style="display:none"/>
<h:inputHidden id="hiddenCountries" value="#{countries.countries}" />
<h:commandButton id="buttonID"
value="Random"
onclick="myArrayList()"/>
</h:form>
</h:body>
#ViewScoped
public class Countries {
private int totalCountries;
private String data = "Afghanistan, Albania, Zimbabwe";
private List<String> countries;
/** Creates a new instance of Countries */
public Countries() {
countries = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(data, ",");
while(st.hasMoreTokens()) {
countries.add(st.nextToken().trim());
}
totalCountries = countries.size();
} //end of constructor
public List<String> getCountries() {
return countries;
}
public void setCountries(List<String> countries) {
this.countries = countries;
}
} //end of class Countries
function myArrayList() {
alert(jQuery('#countries').html());
alert(jQuery('#hiddenCountries').val()) //when using h:inputHidden
} //end of function myArrayList
You can do
<h:inputHidden id="someID" value="#{randomNumber.data}/>
(dont forget to added getter/setter to your data in the bean )
change your onclick of the h:commandButton
onclick="myArrayList()" // or onclick="myArrayList(#{SomeELExpressioGoesHere})"
change your js function into
function myArrayList(inputParam) {
alert(jQuery('#someID').val());
var yourJSString = jQuery('#someID').val();
var myArray = yourJSString.split(','); //when string is Afghanistan,Albania,Zimbabwe (no spaces)
alert(myArray[inputParam]);
}
in order to transfer your js string into array just use
var yourJSString = jQuery('#someID').val()
var myArray = yourJSString.split(','); //when string is Afghanistan,Albania,Zimbabwe (no spaces)
you might be needed to change someID into other id selector if you wont set prependId=false in your form... or simply use a broaded jquery selector like
alert(('input[id$="someID"]').val());
EDIT
Look at my example , you should work with your String data variable and not the countries , cause you should pass the data as string only and not as array... after you will pass the data variable to js you can manipulate it with simple slpit js function to make it back an array in your js... you are getting Conversion Error setting value '[Afghanistan, Albania, Zimbabwe]' for 'null cause you are trying to set String into array... probably the getter of countries converted implicitly the java array into string and when you try to submit it back (string into array) you getting the exception
in order to set from js back to to bean :
jQuery('#someID').val("Some new String goes here");
then when you will submit the form.. the value will be set back to server

Property date must be a valid Date error, when using jquery UI plugin

I have a tasks class, which has a date field. In my view file, I have this line of code :
<g:textField name="date" value="${tasksInstance?.date}" id="datePicker" />
And using the jquery ui plugin, I added this code to my <head> tag :
<g:javascript>
$(document).ready(function()
{
$("#datePicker").datepicker({dateFormat: 'mm/dd/yy'});
})
</g:javascript>
But when I save the date field, I get the following error:
Property date must be a valid Date error
Edit:
Tasks.groovy
package mnm.schedule
class Tasks {
static belongsTo = [ user : User, project: Project ]
String reason
boolean completed
String title
String description
Date date
static constraints = {
user(nullable:false)
completed(nullable:true)
title(nullable:false)
description(size:1..500,nullable:false)
reason(nullable:true)
}
String toString(){
this.title
}
}
And controller action code is :
def save() {
def adminProject = params.managersProject
def foundProject = Project.findByNameLike("$adminProject")
def tasksInstance = new Tasks(params)
foundProject.addToTasks(tasksInstance)
if (!tasksInstance.save(flush: true)) {
render(view: "create", model: [tasksInstance: tasksInstance])
return
}
redirect(action: "show", id: tasksInstance.id)
}
How to recover from this?
I assume you're getting a String like '02/16/2012'? You could just call:
params.date = Date.parse( 'MM/dd/yyyy', params.date )
Before creating the Task object...
There's probably an automatic way of doing this in Grails as well using PropertyEditorSupport
Edit
Also, in grails 2.0, you can do:
def date = params.date( 'myVar', 'MM/dd/yyyy' )
To parse the date param out of the params object
It seems this format does'nt supported with jquery change date format

Show enum values on GSP page and then bind them in the database

I have a use case in which I need to first show the value of enum on the GSP page first as a drop down list, have the user select one of those values and then finally bind the data to the domain.
So my code on GSP looks like my enum is MyEnum
<g:select from="${MyEnum.getAllEnumList()}" optionValue="name" name="duration"/>
my enum is
public enum MyEnum {
MIN15('15 Minutes'),
MIN30('30 Minutes'),
HOUR1('1 Hour'),
HOUR2('2 Hours'),
HOUR5('5 Hours'),
HOUR8('8 Hours'),
HALFDAY('half day'),
FULLDAY('full day')
private final String name
private final String displayName
public static final List<MyEnum> getAllEnumList() {
[MIN15,MIN30,HOUR1,HOUR2,HOUR5,HOUR8,HALFDAY,FULLDAY]
}
public String toString() {
return displayName
}
MyEnum(String name,String displayName) {
this.name = name
this.displayName = displayName;
}
}
when I hit the page its showing an error like:
Error processing GroovyPageView: Error executing tag <g:form>: Error evaluating expression [MyEnum.getAllEnumList()] on line [37]: java.lang.NoClassDefFoundError: Could not initialize class ENUM.MyEnum at D:/myspace/projects/IcepushpluginSampleApp/grails-app/views/util/test.gsp:46
Any ideas ????
This is how I have done it in the past. This way you have i18n support.
gsp
<g:select name="duration" from="${MyEnum.values()}" valueMessagePrefix="ENUM.MyEnum" />
messages.properties
ENUM.MyEnum.MIN15=15 Minutes
ENUM.MyEnum.MIN30=30 Minutes
ENUM.MyEnum.HOUR1=1 Hour
ENUM.MyEnum.HOUR2=2 Hours
ENUM.MyEnum.HOUR5=5 Hours
ENUM.MyEnum.HOUR8=8 Hours
ENUM.MyEnum.HALFDAY=half day
ENUM.MyEnum.FULLDAY=full day
You can avoid importing in your GSP (which is kind of ugly) if you use a custom tag library. You'll also need to add another method (getKey()) to your enum if you want to have the option key be different from its value.
MyEnum.groovy
enum MyEnum {
MIN15('15 Minutes'),
MIN30('30 Minutes'),
HOUR1('1 Hour'),
HOUR2('2 Hours'),
HOUR5('5 Hours'),
HOUR8('8 Hours'),
HALFDAY('half day'),
FULLDAY('full day')
final String displayName
private MyEnum(String displayName) {
this.displayName = displayName
}
String getKey() {
name()
}
String toString() {
displayName
}
}
MyEnumTagLib.groovy
// add import if MyEnum is in a different package
class MyEnumTagLib {
static namespace = 'my'
def enumSelect = { attrs ->
attrs.from = MyEnum.values()
attrs.optionKey = 'key'
out << g.select(attrs)
}
}
gsp
<my:enumSelect name="duration"/>
<%# page import="fully.qualified.path.MyEnum" %>
Try this at the top of your GSP (with the fully qualified path adjusted to your packages, of course).
Edit (this should work (your enum syntax is wrong too)):
<%# page import="ENUM.MyEnum" %>
<html>
<head>
</head>
<body>
<g:select from="${MyEnum.getAllEnumList()}" optionValue="displayName" name="duration"/>
</body>
</html>
And then the revised class:
package ENUM
public enum MyEnum {
MIN15('15 Minutes'),
MIN30('30 Minutes'),
HOUR1('1 Hour'),
HOUR2('2 Hours'),
HOUR5('5 Hours'),
HOUR8('8 Hours'),
HALFDAY('half day'),
FULLDAY('full day')
private final String displayName
public static final List<MyEnum> getAllEnumList() {
[MIN15,MIN30,HOUR1,HOUR2,HOUR5,HOUR8,HALFDAY,FULLDAY]
}
public String toString() {
return displayName
}
MyEnum(String displayName) {
this.displayName = displayName;
}
}
Edit2:
The easiest way to avoid the whole thing (both the second answer here and my solution) is to simply pass off the value list to the gsp from the controller. Simply add
[duration:MyEnum.values()]
or something similar to your controller return.

Resources