Override Grails Error Messages to format Dates and Numbers - grails

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

Related

How do you get strip RTF formatting and get actual string value using DXL in DOORS?

I am trying to get the values in "ID" column of DOORS and I am currently doing this
string ostr=richtext_identifier(o)
When I try to print ostr, in some modules I get just the ID(which is what I want). But in other modules I will get values like "{\rtf1\ansi\ansicpg1256\deff0\nouicompat{\fonttbl{\f0\fnil\fcharset0 Times New Roman;}{\f1\froman\fcharset0 Times New Roman;}} {*\generator Riched20 10.0.17134}\viewkind4\uc1 \pard\f0\fs20\lang1033 SS_\f1\fs24 100\par } " This is the RTF value and I am wondering what the best way is to strip this formatting and get just the value.
Perhaps there is another way to go about this that I am not thinking of as well. Any help would be appreciated.
So the ID column of DOORS is actually a composite- DOORS builds it out of the Module level attribute 'Prefix' and the Object level attribute 'Absolute Number'.
If you wish to grab this value in the future, I would do the following (using your variables)
string ostr = ( module ( o ) )."Prefix" o."Absolute Number" ""
This is opposed to the following, which (despite seeming to be a valid attribute in the insert column dialog) WILL NOT WORK.
string ostr = o."Object Identifier" ""
Hope this helps!
Comment response: You should not need the module name for the code to work. I tested the following successfully on DOORS 9.6.1.10:
Object o = current
string ostr = ( module ( o ) )."Prefix" o."Absolute Number" ""
print ostr
Another solution is to use the identifier function, which takes an Object as input parameter, and returns the identifier as a plain (not RTF) string:
Declaration
string identifier(Object o)
Operation
Returns the identifier, which is a combination of absolute number and module prefix, of object o as a string.
The optimal solution somewhat depends on your underlying requirement for retrieving the object ID.

UILexicon iOS 8 is not working as expected

I am using UILexicon for the suggestions in custom keyboard. Following is code:
-(void) keyTapped:(UIButton*)button {
[self requestSupplementaryLexiconWithCompletion:^(UILexicon *lexicon){
// self.lexicon = lexicon;
NSLog(#"%#",lexicon.entries);
for (UILexiconEntry* entry in lexicon.entries) {
NSLog(#"%#=%#",entry.userInput,entry.documentText);
}
int i=0;
}];
}
But it is returning always same array of entries. Can anyone suggest me how to use it. I will mark correct your answer if it works. Thanks.
It's working but you should implement your own function to compare the UILexiconEntry list with the entered string as stated by apple :
UILexiconEntry
A lexicon entry specifies a read-only term pair, available within a UILexicon object, for use by a custom keyboard.
You can employ a lexicon entry by matching user input against the entry’s userInput value, and then inserting into the current text input object the corresponding documentText value. For example, if the user typed the string “iphone”, the lexicon entry with that exact, case-sensitive string in the userInput property has the string “iPhone” in the corresponding documentText property.
In some cases, the documentText string is in a different text script than the userInput string.

grails and double values saving

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

Delphi & Absolute database : Delete Query

Why is it that my query does not work ?
Form1.ABSQuery1.Close;
Form1.ABSQuery1.SQL.Clear;
Form1.ABSQuery1.SQL.Text:='DELETE FROM LOG WHERE status = ''YES'' and DATE BETWEEN :d1 and :d2';
Form1.ABSQuery1.Params.ParamByName('d1').Value :=cxDateEdit1.Date;
Form1.ABSQuery1.Params.ParamByName('d2').Value :=cxDateEdit2.Date;
Form1.ABSQuery1.ExecSQL;
Form1.ABSTable1.Refresh;
I get this error :
You should be using AsDateTime in your Params setting code.
Form1.ABSQuery1.SQL.Text:='DELETE FROM LOG WHERE status = ''YES'' and DATE BETWEEN :d1 and :d2';
Form1.ABSQuery1.Params.ParamByName('d1').AsDateTime :=cxDateEdit1.Date;
Form1.ABSQuery1.Params.ParamByName('d2').AsDateTime :=cxDateEdit2.Date;
Form1.ABSQuery1.ExecSQL;
Using Value converts the cxDateEdit1.Date to a generic string format for assignment, and that doesn't properly convert it to the YYYY-MM-DD format that most databases (including ABS) expect. Properly using AsDateTime allows the database driver/component to convert to the specific date format the DBMS uses.
Also, is your database field really named DATE? Date is usually a reserved word or function name in most DBMS, and if it is it usually needs to be quoted.
Form1.ABSQuery1.Params.ParamByName('d1').DataType := ftDateTime;
Form1.ABSQuery1.Params.ParamByName('d1').Value :=cxDateEdit1.Date;
You must explicitly specify the data type of the parameter to it had no such problem, and then convert to a string does not need to

Grails intercept form submit to modify params

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!

Resources