Flex: How to make DateChooser show selectedDate - apache-flex

I got a Problem with my DateChooser. When clicking the control directly it highlights the date as it should.
When selecting the date programmatically it won't show.
var date:Date = notification.getBody() as Date;
_view.dcMiniCalendar.selectedDate = date;
trace tells me, that date and _view.dcMiniCalendar.selectedDate carry the correct values.
I already tried to use _view.dcMiniCalendar.invalidateDisplayList() (and some other invalidate functions as well) but neither with nor without them I get that date to be shown selected in the control.
thx in advance.
x_mtd

Are you sure that notification.getBody() returns a valid date?
Mine works just fine.
<mx:DateChooser id="dateChooser" />
<s:Button click="button1_clickHandler(event)" />
protected function button1_clickHandler(event:MouseEvent):void
{
var myDate:Date = new Date(2012, 11, 21);
dateChooser.selectedDate = myDate;
}
What is the return type of notification.getBody() ? If it is a string, parse it using Date.parse()

Related

ASP.NET MVC5 stores date in wrong format

last days I have a quite hard time to convince MVC5 project to work with dates as I would like to. After intensive googling I've tried numerous attepmts to make it work properly, but without success.
Here is the problem:
I need to display and edit dates on my webpage in format dd.MM.yyyy (i.e. 15.07.2015). For editing I also need to use jquery ui datepicker. The thing here is that I've been able to successfully set that datepicker to display date in requested format, also the jquery validation is now correctly validating the date in given format. So as for UI so far so good. The problem appeared in moment, when I clicked submit button - there was an error message like:
The value '15.07.2015' is not valid for Start Date.
After brief investigation I've found that when the date is passed to server it has switched format - instead of dd.MM.yyyy the date is treated like MM.dd.yyyy. In other words the error pops up only when the day part of date is higher than 12.
Here are some highlights from my code:
In my model for date I have this:
[Required]
[Display(Name = "Start Date")]
[DataType(DataType.Date)]
[UIHint("Date")]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateStarts;
Which I believe is everything I need to do to make that date display in specified format and also force users to fill the textbox with date in right format.
As given in [UIHint("Date")], I have my own template for rendering textbox for editing date. The implementation of that template is following:
#model Nullable<DateTime>
#{
DateTime dt = DateTime.Now;
if (Model != null)
{
dt = (System.DateTime)Model;
}
#Html.TextBox("", dt.ToString("dd.MM.yyyy"), new { #class = "form-control datecontrol", type = "text", data_val_date = "Field must have format dd.MM.yyyy" })
<i class="fa fa-calendar form-control-feedback lowerzindex"></i>
}
The jquery datepicker has following implementation:
$('.datecontrol').datepicker({
onClose: function () { $(this).valid(); },
minDate: "-1M",
dateFormat: "dd.mm.yy",
});
So even the datepicker knows how the format should look like.
The last component is the validation by jquery.validation:
$.validator.addMethod(
'date',
function (value, element, params) {
if (this.optional(element)) {
return true;
};
var result = false;
try {
$.datepicker.parseDate('dd.mm.yy', value);
result = true;
} catch (err) {
result = false;
}
return result;
},
''
);
I know that the date is passed to server in some culture neutral format, but I thought that when I decorated code on numerous places with the requested format, this will ensure that the conversion into that culture neutral format will be done right. Or am I missing something else ?
Thanks
Your problem lies in the fact that you have not set proper Culture for your application. Your request end-up executing under culture that has month-day-year order (probably under en-US) causing you a problem.
The easiest solution is to set set the culture that actually has day-month-year order and . as date separator in your web.config, for example:
<configuration>
<system.web>
<globalization uiCulture="de-DE" culture="de-DE" />
...
https://msdn.microsoft.com/en-us/library/bz9tc508%28v=vs.140%29.aspx
The MVC uses current culture when parsing and binding posted data to your models/parameters.
It is advised to use same date separator across entire scope - html, client, javascript, server culture, ...

Get Hidden Field in Code Behind

I have been looking at answers here and other places but so far have not found exactly how to do this.
I have the following definition for a hidden field in my .aspx page:
<asp:HiddenField ID="hfAddressChange" runat="server" />
I set the value in a javascript function on the client:
function confirmAddressChange()
{
if (typeof document.forms[0].hfAddressChange.valueOf ==="undefined")
{
var res = (confirm('"Update Contact Addresses to Rich?"')==true);
document.forms[0].hfAddressChange.valueOf = res;
}
}
Basically I only want to set the value once.
Now I want to check the value in the code behind:
If hfAddressChange.Value <> String.Empty Then
Dim x As String = "Do Something here"
End If
However, even though I have verified that the value IS being set in the js function, it is always an empty string when it gets to my code behind.
Anyone see what the heck I'm doing wrong?
document.forms[0].hfAddressChange.valueOf = res;
The property is value, not valueOf. (And it won't be undefined earlier, either; just check !document.forms[0].hfAddressChange.value.)

Adobe Flex date

Hi I am having a problem in date.
I am having a custom dateChooser.
In the dateChooser component highlights some holidays and at the same time lists the holidays in a container.
The Problem is the date I am displaying in the container is not in ascending order could some one please help.
Link for the demo application with view source enabled
http://125.22.254.206/clients/flexdemos/calendardemo/calendardemo.html
The said logic is implemented in ExtendedDateChooser.as under custome folder.
Are you trying to sort the date in the 'holidayView' vbox?
You cant compare and sort two dates. You can use the date comparison method given below (search the web to find a better one).If the control in the vbox to display holidays is a datagrid, using
<mx:DataGridColumn
headerText="Created Date"
date="createdDt"
sortCompareFunction="date_sortCompareFunc">
</mx:DataGridColumn>
in the tag attribute will result in sortedDate
private function date_sortCompareFunc(itemA:Object, itemB:Object):int
{
/* Date.parse() returns an int, but
ObjectUtil.dateCompare() expects two
Date objects, so convert String to
int to Date. */
var dateA:Date=isoToDate(itemA.createdDt);
var dateB:Date=isoToDate(itemB.createdDt);
return ObjectUtil.dateCompare(dateB, dateA);
}
private function isoToDate(value:String):Date {
var dateStr:String = value;
dateStr = dateStr.replace(/\-/g, "/");
dateStr = dateStr.replace("T", " ");
dateStr = dateStr.replace("Z", " GMT-0000");
return new Date(Date.parse(dateStr));
}
I think, you cant sort by Date.
First, I can't see the container in your app.
My way would be to parse the date in to milliseconds since 1970
parse(date:String):Number
Then you can sort it by some logic.
BR
Frank

How can I put a currencyformatter in a flex datagrid column?

I need to format the column with a currency formatter. I know how to do currency formatting I just need an example on how to implement it into the datagrid column.
No need to use an itemRenderer. Just use a labelFunction. Example:
The DataGridColumn:
<mx:DataGridColumn headerText="Total Cost" dataField="TotalCost" labelFunction="LabelFormatter"/>
LabelFormatter label function:
protected function LabelFormatter(item:Object, column:DataGridColumn):String
{
var returnLabel:String = "";
var header:String = column.headerText;
switch (header)
{
case "Total Cost":
returnLabel = currencyFormat.format(item.TotalCost.toString());
break;
}
return returnLabel;
}
The Currency Formatter:
<mx:CurrencyFormatter id="currencyFormat" precision="2" />
Or:
private function formatarValor(item:Object, coluna:DataGridColumn):String{
return realFormatter.format(item[coluna.dataField]);
}
An ActionScript based answer that doesn't require defining an additional function:
var currencyFormatter:CurrencyFormatter = new CurrencyFormatter();
var gridCol:GridColumn = new GridColumn("My Money");
gridCol.dataField = "amount";
gridCol.formatter = currencyFormatter;
From the Adobe docs, the labelFunction property is useful for performing more complex tasks, such as combining two fields from the data provider into one column. But for a simple task such as formatting currency values, the above code is sufficient.

Preserve multi-column sort in AdvancedDataGrid with dataProvider as GroupingCollection

I have three attributes in my XML object: last name, first name, and age.
My sample XML looks like:
<dataXML>
<info last="Abc" first="Def" age="20"/>
<info last="Abc" first="Hij" age="10"/>
<info last="Xyz" first="Klm" age="25"/>
<info last="Xyz" first="Opq" age="64"/>
<info last="Xyz" first="Rst" age="08"/>
</dataXML>
I am using Grouping Collection and AdvancedDataGrid to show the data.
My problem is to preserve multi-column sort.
After a refresh happens, the user selected sorting order goes away, and the grid gets sorted by first column only.
So suppose, user has sorted the table, first ascending by "Age" and then descending by "Name"; after a refresh happens, the grid again gets sorted ascending by "Name".
I don't want the refresh event to change the sort order, only the data should get refreshed.
Thanks in advance.
P.S. I can't use any other datatype like ArrayCollection, to store the data.
Part of my code looks as follows:
<mx:Script>
<![CDATA[
[Bindable]
private var dataXML:XMLListCollection = new XMLListCollection();
private function refresh(data:Object):void
{
dataXML.source = XML(data.result.value).info;
gc.refresh();
adGrid.dataProvider = gc;
adGrid.validateNow();
adGrid.dataProvider.refresh();
}
private function nameCompareFunction(a:XML, b:XML):int
{
return ObjectUtil.stringCompare(a.attribute("last") + a.attribute("first"), b.attribute("last") + b.attribute("first"));
}
private function valueSortCompareFunction(a:XML, b:XML):int
{
return ObjectUtil.numericCompare(Number(a.attribute("age")), Number(b.attribute("age")));
}
]]>
</mx:Script>
<Control:AdvancedDataGrid id="adGrid">
<Control:dataProvider>
<mx:GroupingCollection id="gc" source="{dataXML}">
<mx:grouping>
<mx:Grouping>
<mx:GroupingField name="#last" compareFunction="nameCompareFunction"/>
</mx:Grouping>
</mx:grouping>
</mx:GroupingCollection>
</Control:dataProvider>
<Control:columns>
<mx:AdvancedDataGridColumn id="ADGCName" dataField="#first" headerText="Name" wordWrap="true"/>
<mx:AdvancedDataGridColumn id="ADGCAge" dataField="#age" headerText="Age" sortCompareFunction="valueSortCompareFunction"/>
</Control:columns>
</Control:AdvancedDataGrid>
before the refresh (or when the sorting options are changed at all) store the current sort options, they are actually on the dataprovider.
var objDp:HierarchicalCollectionView = ucADG.dataProvider as HierarchicalCollectionView;
the current SortField objects are on objDp.sort.fields in this case.
after the collection is refreshed just do the opposite. For example:
var objDP:HierarchicalCollectionView = ucADG.dataProvider as HierarchicalCollectionView;
if(objDP != null)
{
var objSort:Sort = new Sort();
objSort.fields = [ new SortField("SomeField", true, bUseDescending) ];
objDP.sort = objSort;
objDP.refresh();
}
I had this same problem, and based on JtheGeek's and rocksoccer's answers, I was able to preserve the sort order.
My set-up is a bit different. I have a var _xmlListData:XMLListCollection that is bound directly to AdvancedDataGrid.dataProvider. My refresh function simply does this:
var sort:Sort = _xmlListData.sort;
_xmlListData.source = data as XMLList;
_xmlListData.sort = sort;
And it works. So, I wonder if doing the same thing to your XMLListCollection before calling gc.refresh() would have the same results? I.e.:
private function refresh(data:Object):void
{
var sort:Sort = dataXML.sort;
dataXML.source = XML(data.result.value).info;
dataXML.sort = sort;
gc.refresh();
adGrid.dataProvider = gc;
adGrid.validateNow();
adGrid.dataProvider.refresh();
}
I think JTtheGeek's anwser is not quite correct. The code would just work when you sort on one column. Because except the descending order, you also need to remember the priority between different columns in sorting.
In fact, it is so easy, create a temp sort object to store the sort in the dataProvider, and then restore it after you apply the new dataProver, then refresh it.

Resources