Why do I need this:
I am working in a project which allows user to choose date in Nepali Bikram Sambat Date format (which is incompatible with Java and SQL's "DATE"). I did it by modifying org.codehaus.groovy.grails.plugins.web.taglib.FormTagLib class's datePicker tagLibrary. And modifying the scaffolding template list.gsp.
My problem :
When user chooses Nepali date from browser and submits the form, I want to read the [day, month, year] and convert it into Java Date object and save into database. (The date will be converted back to Nepali Bikram Sambat when it will be displayed into view).
I tried to print the params in the controller but all the params are already mapped/wrapped into corresponding objects - along with my Nepali Date. So I get sysout of Java's Date from code below :
println params.date
I am wondering how can I intercept the form submit request and modify the date params into English date. I see one solution - using JavaScript ( and rewrite my conversion code into JavaScript) before form submit to convert the params. And just wanted to confirm is there a easy way - like interceptor/filter etc.
Well, assuming you are using input fields with the standard grails datepicker, you should have in your params map the fields being passed, just with a different name. Write a "println params" in your action receiving the request and look for the names of the fields of the datepicker. It was supposed to bring you something like (name of the datepicker field, say * + _year, for year, * + _month for month and so on).
You can create a CustomEditorRegistrar that changes the format from your date before it's wrapped into objects. Like this:
public class CustomDateEditorRegister implements PropertyEditorRegistrar {
public void registerCustomEditors(PropertyEditorRegistry registry) {
String dateFormat = 'dd/MM/yyyy'
registry.registerCustomEditor(Date, new CustomDateEditor(new SimpleDateFormat(dateFormat), true))
}
}
And your Date editor could be something like:
class CustomSimpleDateEditor extends CustomDateEditor {
public CustomSimpleDateEditor(SimpleDateFormat formatter, boolean allowEmpty) {
super(formatter, allowEmpty);
}
public String getAsText() {
Date date = (Date)getValue();
try {
String dateText = new SimpleDateFormat("dd/MM/yyyy").parse(date);
return dateText;
}
catch(Exception e) {
e.printStackTrace();
return "";
}
}
}
Your params.date will be converted before it's passed to objects and saved to the db. Anyway, here's a good link explaining it.
Hope it helps!
Related
Situation and problem, short
The LocalDateTimeRenderer in Vaadin 21 shows a German date in a German browser, even if the Locale in the Vaadin session is changed to e.g. Locale.UK.
Situation and problem, long / detailled
In a Vaadin 21 Grid I've got a column for LocalDateTime. It's created like this for an entity type T:
private <T> Column<T> addLocalDateTimeColumn(Grid<T> grid, ValueProvider<T, LocalDateTime> getter) {
LocalDateTimeRenderer<T> renderer = new LocalDateTimeRenderer(getter);
Column<T> column = grid.addColumn(renderer).setAutoWidth(true);
return column;
}
When I change the Locale in the session by calling UI.getCurrent().getSession().setLocale(locale); the whole application is translated into the new language, but not the content of the LocalDateTime-column.
Refreshing the whole Grid by calling grid.getDataProvider().refreshAll() (see here Vaadin 21: re-translate column with ItemLabelGenerator on locale change ) causes the ValueProvider in the code example above to get called again (a good indicator I think) but it does not format the LocalDateTime in the new selected language (this is the unexpected behavior).
So even if the locale in the session is English / Locale.UK, the LocalDateTime value is formatted in German like this:
Using a localized DateTimeFormatter like this LocalDateTimeRenderer<T> renderer = new LocalDateTimeRenderer(getter, DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.SHORT)); also did not help: the style was different but the months were still translated German.
Workaround
Using a custom TextRenderer works (= column LocalDateTime content is translated with the session's locale):
private <T> Column<T> addLocalDateTimeColumn(Grid<T> grid, ValueProvider<T, LocalDateTime> getter) {
Renderer<T> renderer = new TextRenderer<T>(new ItemLabelGenerator<T>() {
#Override
public String apply(T entity) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd. MMMM yyyy HH:mm", UI.getCurrent().getLocale());
return getter.apply(entity).format(formatter);
}
});
Column<T> column = grid.addColumn(renderer).setAutoWidth(true);
return column;
}
Question
Is there some trick to get the same result with Vaadins LocalDateTimeRenderer?
No, it's not possible to change the locale of a column dynamically if you're using LocalDateRenderer or LocalDateTimeRenderer in Vaadin 21 or Vaadin 22. This is because of the following:
The locale isn't explicitly saved in the Renderer. The Locale given to the renderer constructor (or the default) is used to produce a Formatter, which is saved into the field private DateTimeFormatter formatter;
The formatter doesn't have any getters or setters.
Even if the Locale of the VaadinSession changes, the formatter's locale stays the same as what it was created with
You can't change the Renderer of a Column to something else after its creation.
What you can do is remove the Column and re-add it with a new LocalDate(Time)Renderer with the requested Locale.
I'd recommend creating a feature request about this in https://github.com/vaadin/flow-components/
In my Grails project I have a Domain Class with a double field as follows:
double totalAmount;
the value of this field are calculated by a sum done after selecting values in a multiple select. the function for sum values is in the controller, as follows:
def sumReceiptItems(){
params.list("receiptItemsSelected").each {i-> println("element "+i)}
def appList = params.list("receiptItemsSelected")
List<ReceiptItem> allSelectedIds = ReceiptItem.findAllByIdInList(params.receiptItemsSelected.split(',')*.toLong())
def totalAmount = allSelectedIds.amount.sum()
println("totalAmount is = "+totalAmount)
render totalAmount as Double
}
the function works well. After function calling, to update the field in GSP page, I use a javascript method as follows:
function updateTotalAmount(name, data, presentNullAsThis){
if(data !=null)
document.getElementById(name).value= data;
else
document.getElementById(name).value=presentNullAsThis;
}
The javascript works and I see the updating of the field at runtime, but the double value is shown with a dot, and not with comma to separate decimal values. Infact, after clicking by save button to save the instance of the domain class, the value is saved without separating decimals, for example:
if the value into the fiels is 10.50 it is stored as 1050
In this discussion how can save a double type correctly in grails? I've read a similar problem, but solution is not good for my issue.
Anybody can help me?
Values with decimal separator depends on the current Locale of the user. Normally you use g.formatNumber in the view to display correctly the value.
You can check this topic on how to discover the decimal separator for a Locale.
To get the user's Locale use:
Locale locale = RequestContextUtils.getLocale(request)
I have solved the problem in this way:
I've updated my Javascript as follows:
function updateTotalAmount(name, data, presentNullAsThis)
{
var data2 = data.toString().replace(/\./g, ',');
if(data2 != null) document.getElementById(name).value= data2;
else document.getElementById(name).value= presentNullAsThis;
}
I've removed "type="number"" in the gsp related field
I'm using Grails 1.3.4 with the export 0.9.5 plug in.
I have a formatter that I use that sets the date format to 'YYYY-MM-DD' when exporting to excel. But this doesn't change the data type. The date is exported to Excel as a string/general data type.
def dateFormat = { domain, value ->
if(value instanceof Date){
return new java.text.SimpleDateFormat("yyyy-MM-dd").format(value)
}
return value
}
Map formatters = [ecd:dateFormat, completed:dateFormat, dateCreated:dateFormat, approvedDate:dateFormat, dpaECD:dateFormat]
exportService.export(params.format, response.outputStream,exportList, jobService.parseColNames(columns), labels, formatters, null)
Is there a way to export data and set the datatype of a column in excel so the user doesn't have to manually set the cell/column formatting to 'Date' every time after exporting?
Are you sure you want to use that plugin? It didn't work so well to me.
I've been using the JXL plugin for Grails for a while and it works perfectly.
It even has an option to write the Excel file to the response, so that the user can directly download the file using my REST service.
The link is: http://grails.org/plugin/jxl
Here is an example of how simple it is to create workbooks:
new ExcelBuilder().workbook('/path/to/test.xls') {
sheet('SheetName') {
cell(0,0,'Current Date')
cell(0,1,new Date())
}
}
Note that the cell() method has 3 parameters: column, row and value. This third parameter can be a number, string or date, and it formats it perfectly.
You can find more information here.
I have created a domain with a Double field. When the validation occurs it throws the error message with size value showing the number with commas. Following are the detials
Groovy Class
class Quote {
String content;
Double size;
static constraints = {
content(maxSize:1000, blank:false)
size(min: 0.00D, max:999.99D)
}
}
Value entered "11111", error obtained "Size 11,111 is exceeded the limit". I have added the property key/value pair in messages.properties.
Here, I would like to get the message back without the commas. My main aim is to take the key and format the message returned based on my requirements. I require this as I have other fields that need conversion. For example, a date is validated but when showing the error the Gregorian date needs to be converted to an Islamic date and shown to user.
Does anyone know if I can do something to make this work.
I have tried the solution provided in http://ishanf.tumblr.com/post/434379583/custom-property-editor-for-grails but this did not work.
I have also tried modifying the messages values, but this is not flexible in case of my date issue. Example, for a key value pair, instead of using {2} as a place holder I could use {2, date, mm/dd/yyyy}, but for Islamic dates I want to format and show things differently.
Also, please note I have created a separate key for default date formatting for my application.
Would appreciate the help.
In grails, the return of a constrain is an already translated string.
You can create a taglib to format that, or enhance the
Another option would be custom validators. A custom validator can return false or a key when failing.
For example in your domain class, to vaildate a field:
myDateField validator: {val, obj -> obj.myShinyDateValidatorMethod(val) }
private myShinyDateValidatorMethod() {
if (isNotValidDate(val) {
return [the_message_key, val.formatedAsYouWand]
}
}
and, in your properties file you have to have defined the key:
the_message_key=This date: {3} is not valid
The trick here is that in the return from the validator, first string is the key and the rest are parameters for that key, but grails already uses {0}, {1}, {2} placeholders for className, fieldName and value, and the first parameter that you pass will be used as {3} placeholder.
Hope this helps
I'm new to Grails. I have a field in my domain object which I define as an String.
String ponum
When i click first time on create page ,the "ponum" field has to display 0001 and later it has to save in database.And When i click on second time the "ponum" field has to display 0002 and later it has to save in database.Everytime i click on create page "ponum" field has to autoincrement and save it database.I google ,but i did not get any document.
thanks
As things get an id anyway (assuming your using a regular rdbms with standard id genaerator), why not just pretend there's a variable ponum which is based on the id?
Just add a getter to your domain class:
class Page {
String getPonum() {
String.format( "%04d", id )
}
}
According to this answer, it is not possible to use hibernate generators (those used for ids) to do that. If you really need to use Hibernate generators, a workaround is described in the answer as well.
In your case, you could use an interceptor to generator your ponum property when inserting a new object:
class Yours {
int ponum
def beforeInsert() {
def lastPonum = Book.list([sort: 'ponum', order:'desc', max: 1])
if(lastPonum)
ponum = (lastPonum.pop().ponum as int) + 1 as String
else
ponum = '0'
}
}