inputText and convertDateTime error - jsf-2

I have an h:inputText field which I use to enter a date. I am using the f:convertDateTime but I get errors.
Here is the situation:
<h:inputText value="#{listModel.creationDate}" valueChangeListener="#{listController.filterFieldChanged}">
<f:convertDateTime type="date" pattern="yyyy-MM-dd"/>
</h:inputText>
If I enter "2011-11-23" I get the following error:
"...[exec] sourceId=j_idt3[severity=(ERROR 2), summary=(Conversion Error setting value 'Wed Nov 23 01:00:00 CET 2011' for 'null Converter'. ), detail=(Conversion Error setting value 'Wed Nov 23 01:00:00 CET 2011' for 'null Converter'. )]|#]" (besides, where does 01:00:00 come from??)
If I remove the type="date" and leave only pattern="yyyy-MM-dd" and enter the same date, I get the same error.
If I remove the pattern and leave only type="date" and enter the same date, I get the following error:
"[exec] sourceId=searchForm:j_idt72[severity=(ERROR 2), summary=(searchForm:j_idt72: '2011-11-23' could not be understood as a date.), detail=(searchForm:j_idt72: '2011-11-23' could not be understood as a date. Example: 23.11.2011 )]|#]"
I am a little confused. If I define the pattern yyyy-MM-dd why "2011-11-23" isn't accepted?
Info added:
value="#{listModel.creationDate}"
public Date getCreationDate()
{
return creationDate;
}
This is the getter for creationDate in the class ListModel. (it is a java.Util.Date)
valueChangeListener="#{listController.filterFieldChanged}"
public void filterFieldChanged( ValueChangeEvent event )
{
// Note: value change events are handled in the PROCESS_VALIDATIONS
// phase by default. The problem is that the model values are not
// updated until later, so any changes we make here would normally be
// overwritten.
// By requeueing the event and targeting it to the UPDATE_MODEL_VALUES
// phase we can make the model changes without them being overwritten.
if ( event.getPhaseId().equals( PhaseId.ANY_PHASE ) )
{
event.setPhaseId( PhaseId.UPDATE_MODEL_VALUES );
event.queue();
}
else
{
// reset the paging any time a filter field was changed
listModel.setFirstResult( 0 );
}
}
I hope this is useful...

Related

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'

I have kendo date picker and a div, which showing "Required" message in angular4 reactive form.
<kendo-datepicker #datePicker=appDateFormat
[(value)]="questionControlInfoData.currentValue"
[format]="dateFormat"
[formatPlaceholder]="{ year: 'yyyy', month: 'mm', day: 'dd' }"
[formControlName]="questionControlInfoData.formControlName" [disabled]="questionControlInfoData.disabledControl"
[appDateFormatOnly]="dateValidationFormat"> </kendo-datepicker>
<div> <span *ngIf="!isValid()" [class.star]="!isValid()">This field is required</span> </div>
The reactive form is loading the controls dynamically.
The "appDateFormatOnly" is a directive used for date format validation.
I have a method "isValid()", which is returning one boolean value based on some condition.
isValid() {
var dateValue = this.qnaFormGroup.controls[this.questionControlInfoData.formControlName].value;
var hasDateValue = (dateValue !== undefined && dateValue !== "");
if (hasDateValue && !this.datePickerDirective.isValid) {
this.qnaFormGroup.controls[this.questionControlInfoData.formControlName].setErrors({ 'invalidDate': true });
}
var isValid = this.qnaFormGroup.controls[this.questionControlInfoData.formControlName].touched ? this.qnaFormGroup.controls[this.questionControlInfoData.formControlName].valid
: this.qnaFormGroup.controls[this.questionControlInfoData.formControlName].dirty ? this.qnaFormGroup.controls[this.questionControlInfoData.formControlName].valid : true;
return hasDateValue || isValid;
}
Inside this "isValid()" method I am adding error to the control based on some condition using the "setErrors" angular4 method.
The"isValid()" is called if anything changed in this reactive form.
The issue is:
Sometimes I am getting the error "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'." while typing the date value in the date picker..
I have analyzed and found that the issue is with adding error in the form control using "setErrors" method.
Could you please someone give any solution for this problem.

Grails accessing data where dates equal in database first mode

I'm returning to Grails after a year hiatus while I worked for .Net shop. I had always programmed Grails in code first mode. My newest project is database first, and I thought I was ready. I have a simple calendar table in my MySql database:
commit;CREATE TABLE `Calendar` (
`ID` bigint(20) NOT NULL,
`Title` varchar(200) NOT NULL,
`EventDate` date NOT NULL,
`StartTime` time DEFAULT NULL,
`EndTime` time DEFAULT NULL,
`Location` varchar(500) NOT NULL,
`version` int(11) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
With the following data in the table:
insert into Calendar (Title, EventDate, StartTime, EndTime, Location, version)
values ('Summer 2016 Garage Sale', '2016-07-23', '7:00 ', '19:00', 'Lodge', 0);
insert into Calendar (Title, EventDate, StartTime, EndTime, Location, version)
values ('August 2016 Member Meeting', '2016-08-03', '19:00', '20:00', 'Lodge', 0);
commit;
My calendar class in Grails looks like:
package plaquemineelks
import java.sql.Time
import grails.validation.Validateable
#Validateable
class Calendar {
Long id
Integer version
String title
Date eventDate
Time startTime
Time endTime
String location
static constraints = {
title (blank: false)
eventDate (blank: false)
location (blank: false)
}
static mapping = {
table "Calendar"
id column: "ID"
version column: "version"
eventDate column: "EventDate"
startTime column: "StartTime"
endTime column: "EndTime"
location column: "Location"
}
}
My controller looks like:
package plaquemineelks
class CalendarController {
def index() { }
def getByDate(String EventDate) {
def Date newDate = Date.parse("mm/dd/yyyy", EventDate)
def results = Calendar.findAllByEventDate(newDate)
render(contentType: 'text/json') {[
'results': results,
'status': results ? "OK" : "Nothing present"
]}
}
}
When I run the app and open the URI
http://localhost:8080/PlaquemineElks/Calendar/getByDate?EventDate=07/23/2016
My Json looks like:
{"results":[],"status":"Nothing present"}
I have tried a variety of formats, etc. for the date, keeping it groovy. I'm sure I'm missing something simple.
Thanks for any assistance.
You are inserting data to your table using sql query which means by default the StartDate contains date only and 00:00:00 for timestamp. Otherwise it will consider the timezone also if you insert into it using GORM.
First thing that you need to do is set the time zone to UTC for your application. In Bootstrap.grooy:
TimeZone.setDefault(TimeZone.getTimeZone('UTC'))
Secondly the format mm/dd/yyyy that you are using to parse the date is wrong, it should be: MM/dd/yyyy.
println Date.parse("mm/dd/yyyy", "07/23/2016")
Sat Jan 23 00:07:00 UTC 2016 //wrong
println Date.parse("MM/dd/yyyy", "07/23/2016")
Sat Jul 23 00:00:00 UTC 2016 //correct

Display a string in place of a NULL date

when the date property is set in the model, this is executed:
if (!(rdr["JobEnded"] is DBNull)) { job.JobEnded = (DateTime)rdr["JobEnded"]; }
which results in job.JobEnded being 1/1/0001 12:00:00 AM.
What can I use in place of
#Html.DisplayFor(modelItem => item.JobEnded)
to show "In Progress" instead of "1/1/0001 12:00:00 AM".
I've tried putting an if/else in the view, but was only able to display a valid date or nothing. I'm sure I'm missing something really basic here as this is my first attempt at an APS.NET MVC view.
You're dealing with default dates here, so to test for it, you need to use:
#if (item.JobEnded == default(DateTime))
{
#:In Progress
}
else
{
#Html.DisplayFor(m => item.JobEnded)
}
Or in one-liner form:
#((item.JobEnded == default(DateTime)) ? "In Progress" : Html.DisplayFor(m => item.JobEnded).ToString())

Edit Data Table Value adds extra row

<p:column headerText="Cancel" width="60">
<p:commandLink actionListener="#{userLeaveBean.cancelForLeave}" title="Cancel Request" process="#this" update="leaveDataTable" disabled="false">
<h:graphicImage url="resources/images/cancel.gif"/>
<f:attribute name="userId" value="#{employee.name}"/>
<f:attribute name="leaveId" value="#{leaveDetails.strLeaveId}"/>
</p:commandLink></p:column>
Hi I have written this code to modify a row value of a data table. The method that invoked named 'cancelForLeave' modifies the detail of the row value of the data table.The method is as follows:
public void cancelForLeave(ActionEvent actionEvent){
String userId = (String)actionEvent.getComponent().getAttributes().get("userId");
String leaveId = (String)actionEvent.getComponent().getAttributes().get("leaveId");
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
ConnectLdap connectLdap = new ConnectLdap();
UserTotalLeaveInfoBean userTotalLeaveInfoBean = connectLdap.getUserLeaveBean(""+currentYear, userId);
if(userTotalLeaveInfoBean != null){
UserGeneralLeaveDetailsBean[] userGeneralLeaveDetailsBean = userTotalLeaveInfoBean.getArrUserGeneralLeaveDetailsBean();
if(userGeneralLeaveDetailsBean != null){
for(int i=0;i<userGeneralLeaveDetailsBean.length;i++){
String beanLeaveId = userGeneralLeaveDetailsBean[i].getStrLeaveId();
if(leaveId.trim().equalsIgnoreCase(beanLeaveId)){
if(userGeneralLeaveDetailsBean[i].getStrLeaveStatus().trim().equalsIgnoreCase(LeaveStatus.LVST_APPLIED)){
userGeneralLeaveDetailsBean[i].setStrLeaveStatus(LeaveStatus.LVST_CANCELED);
}if(userGeneralLeaveDetailsBean[i].getStrLeaveStatus().trim().equalsIgnoreCase(LeaveStatus.LVST_APPROVED)){
userGeneralLeaveDetailsBean[i].setStrLeaveStatus(LeaveStatus.LVST_CANCELREQ);
}
userTotalLeaveInfoBean.setArrUserGeneralLeaveDetailsBean(userGeneralLeaveDetailsBean);
connectLdap.addAppliedLeaveInLdap(userTotalLeaveInfoBean, ""+currentYear, userId);
leaveDetails.add(userGeneralLeaveDetailsBean[i]);
}
}
}
}
}
private List<UserGeneralLeaveDetailsBean> leaveDetails;
//Getter and Setter
Now the problem is that, When I click on the image button it modifies the value for the row, but adds an extra row in the data table with the modified value. But when I Logout and then Again login,it shows there is no extra row, and the row I attempted to modify shows nicesly with the modified value.
what should be done to prevent the extra row addition at run time, while attempting for the value change of the data table row?Please Help!!
I get the following Log Details: If I put a Log in the page:
Monday, June 03, 2013 3:59:55 PM : Initiating ajax request.
Monday, June 03, 2013 3:59:55 PM : Form to post applyLeaveForm.
Monday, June 03, 2013 3:59:55 PM : URL to post /DemoApplication/applyLeave.xhtml.
Monday, June 03, 2013 3:59:55 PM : Post Data:javax.faces.partial.ajax=true&javax.faces.source=applyLeaveForm%3AleaveDataTable%3A0%3Aj_idt90&javax.faces.partial.execute=applyLeaveForm%3AleaveDataTable%3A0%3Aj_idt90&javax.faces.partial.render=applyLeaveForm%3AleaveDataTable&applyLeaveForm%3AleaveDataTable%3A0%3Aj_idt90=applyLeaveForm%3AleaveDataTable%3A0%3Aj_idt90&applyLeaveForm=applyLeaveForm&applyLeaveForm%3AfromDate_input=&applyLeaveForm%3AtoDate_input=&applyLeaveForm%3Aj_idt59=morning&applyLeaveForm%3Aj_idt60=endofday&applyLeaveForm%3AleaveDataTable%3A0%3AeditFrom_input=03-Jun-2013&applyLeaveForm%3AleaveDataTable%3A0%3Aj_idt68=morning&applyLeaveForm%3AleaveDataTable%3A0%3AeditTo_input=04-Jun-2013&applyLeaveForm%3AleaveDataTable%3A0%3Aj_idt72=endofday&javax.faces.ViewState=-3803632482959899224%3A-5634910090194656061
Monday, June 03, 2013 3:59:55 PM : Response received succesfully.
Monday, June 03, 2013 3:59:56 PM : DOM is updated.
Monday, June 03, 2013 3:59:56 PM : Response completed.
You don't need to add the modified item back to your list :
leaveDetails.add(userGeneralLeaveDetailsBean[i]);
You must remove this line and it should fix your problem. You are updating your source the line just before, and the add only apply in the current view, that's why refreshing get the right data.
Also your bean must be at least in #ViewScoped or #SessionScoped.

Working with dates in breeze

I'm having some trouble working with dates.
I have an object with a date field:
public DateTime FechaInicio{get; set;}
This definition generates the following field in the database:
FechaInicio datetime not null
Making the request to the web service I get the date ( in the JSON ) in the following format:
"FechaInicio": "1982-12-02T00: 00:00"
And calling FechaInicio() on tne entity returns a javascript Date object.
Creating a new entity I get the following value:
createPalanca var = function () {
MetadataStore var = manager.metadataStore;
metadataStore.getEntityType palancaType = var ("Toggle");
palancaType.createEntity newPalanca = var ();
manager.addEntity (newPalanca);
//Here: newPalanca.FechaInicio () has the value in this format: 1355313343214
//Expected Date object here
newPalanca return;
};
After all, my real question is: What format should I use to assign new values ​​to date type fields?
Edit:
After doing some tests, I noticed that if I assign a Date object to the property, everything seems fine until we got to this line:
saveBundleStringified var = JSON.stringify (saveBundle);
saveBundle content is:
FechaInicio: Thu Dec 20 2012 00:00:00 GMT+0100 (Hora estándar romance)
and the saveBundleStringified:
"FechaInicio": "2012-12-19T23:00:00.000Z" <- I guess this is utc format
What finally is stored in the database is: 2012-12-19 23:00:00.0000000
When the result of the call to SaveChanges are returned , they are merged with the entities in cache at the function updateEntity which does this check: if (!core.isDate(val)) that returns false.
As a consequence it is created a new Date object with the wrong date:
function fastDateParse(y, m, d, h, i, s, ms){ //2012 12 19 23 00 00 ""
return new Date(y, m - 1, d, h || 0, i || 0, s || 0, ms || 0);
}
Correct me if I'm wrong, but I think that's the problem.
Sorry for taking so long...
There were bugs with Breeze's DateTime timezone serialization and the default DateTime values used for newly constructed entities with non-nullable date fields. These are fixed as of v 0.77.2. Please confirm if this set of fixes works for you.
And thanks for finding these.
And to answer your question, all date properties on your object should be set to javascript Dates. Breeze should handle all of the serialization issues properly.
Dates always scare me. My immediate instinct is that the browser and server are not on the same TimeZone; how that could be I don't know. In any case, it's bound to happen and I recall all kinds of fundamental problems with coordinating client and server on datetime. I think the usual recommendation has always been to keep everything in UTC and adjust what you display to the user in local time.
I rather doubt this is a helpful answer. I'm not sure what part Breeze should play in resolving this. Would welcome a suggestion that we can circulate and build consensus around.
Also can you clarify this statement:
When the result of the call to SaveChanges are returned , they are merged with the entities in cache at the function updateEntity which does this check: if (!core.isDate(val)) that returns false. As a consequence it is created a new Date object with the wrong date
What do you mean by "the wrong date"? And are you saying that Breeze thinks the incoming date value is in an invalid format (as opposed to being a date other than the one you expected)?
Yes, #Sascha, Breeze is using the Web Api standard for JSON formatting (Json.Net) and it is set for ISO8601 format as opposed to the wacky Microsoft format (which escapes me as I write this).
Breeze/Web Api seem to need the dates in some special format (ISO8601). Any other format did not work for me. moment.js solved the problem for me with setting and reading. Formatting is also nicely done if you use Knockout to display the date with a special binding.
entity.someDate(moment().utc().toDate()) // example
and it works.
You could also use this:
Date.prototype.setISO8601 = function(string) {
var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
var d = string.match(new RegExp(regexp));
var offset = 0;
var date = new Date(d[1], 0, 1);
if (d[3]) {
date.setMonth(d[3] - 1);
}
if (d[5]) {
date.setDate(d[5]);
}
if (d[7]) {
date.setHours(d[7]);
}
if (d[8]) {
date.setMinutes(d[8]);
}
if (d[10]) {
date.setSeconds(d[10]);
}
if (d[12]) {
date.setMilliseconds(Number("0." + d[12]) * 1000);
}
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= ((d[15] == '-') ? 1 : -1);
}
offset -= date.getTimezoneOffset();
time = (Number(date) + (offset * 60 * 1000));
this.setTime(Number(time));
};

Resources