Grails GSP tab fieldValue formatting - spring

How does the Grails tag fieldValue perform its formatting?
I have an domain class with an Double attribute.
class Thing {
Double numericValue
}
In GSP, the fieldValue is used (as created by grails generate-all) for rendering:
${fieldValue(bean:thing, field:"numericValue")}
Unfortunately digits after 3 decimal places are not displayed (ie, 0.123456 is displayed as 0.123). How do I control fieldValue's formatting?
Note that I could just use ${thing.numericValue} (which does no formatting) or
<g:formatNumber>, but I'd rather use the fieldValue tag and specify the formatting. I just don't know where to specify fieldValue's formatting.

Use
<g:formatNumber number="${thing.numericValue}" format="\\$###,##0.00" />
instead or use
${g.formatNumber(number:thing.numericValue, format:'\\$###,##0.00'}
Hope this helps.

An alternative to the answers above is using the i8n files. This option is useful since it can be changed for "All" and depending on the locale
if you go to the messages.properties file you can add the following
default.number.format = ###,##0.00
This will change the default format for all numbers.
If you plan on using the g:formatNumber tag i would suggest using it as
<g:formatNumber number="${myNumber}" formatName="myCustom.number.format" />
and adding the code entry to the messages.properties files as:
myCustom.number.format = ###,##0.00
by doing this you will only need to use the code wherever you need a similar number format, and, if needed make the changes in a single place.
It would be in your best interests to read this article from the grails docs.
OFFTOPIC: As a side note you can also change the default date format in the messages.properties file as follows
default.date.format=dd 'de' MMMM 'de' yyyy

Related

In Freemarker Change output date format irrespective of input format

${(.vars["OCRResponse"].Date)?datetime("ANY RANDOM FORMAT")?string("mm-dd-yy").
Can we use If Else within ?datetime, or can we resolve this by using switch case?
If that date format is quite "random", and you need to do this a lot, then you are probably better of writing a freemarker.core.TemplateDateFormat+TemplateDateFormatFactory implementation, do the complex date parsing logic in Java, then register the factory as a "custom date format" (that's a FreeMarker configuration setting), let's say with name "random". Then you can do ${OCRResponse.Date?date.#random?string('MM-dd-yy')}. If you set the date_format configuration setting to MM-dd-yy, then you can even just write ${OCRResponse.Date?date.#random}.
You can find concrete examples of defining a custom formats here: https://freemarker.apache.org/docs/pgui_config_custom_formats.html
Another possibility is to use #if/#elseif/#else of course. If you need to do that on multiple places, then put your parser logic into a #function, where you #return the parsed date. So where you insert a date you just have something like ${parseRandom(OCRResponse.Date)} (here I have assumed that date_format is MM-dd-yy, otherwise add ?string('MM-dd-yy')).

How to format CRM "Date Only" field to string with Freemarker?

Im trying to build a email template with Freemarker/Clickdimensions plugin in CRM 2013. I have a "Date only" field on an entity which for example contains the date 2017-04-17. I want this date to show as the following: Monday 17 april.
This is done with Freemarker and I have tried the following:
<#assign x = Recipient.field_booking.field_scheduleddate?time>
${x?string.full}
This doesnt seem to work. Im not getting any result at all, just an empty line.
Does anyone know what could be wrong?
I will assume that field_scheduleddate is a string (not a java.util.Date).
At ?time FreeMarker should throw and exception saying something like that the string doesn't follow the expected pattern. I suspect the framework you are using catches and suppresses that exception (which makes using FreeMarker much much harder). Check the logs, maybe it's there.
You want to deal with a date-only value there, hence you should use ?date, as ?time is for time-only values. Also, field_scheduleddate apparently uses ISO 8601 format, so unless the date_format configuration setting is set to ISO, you will have to use ?date.iso (supported since FreeMarker 2.3.21).
As of printing the date, ?string.full should work, but usually you should set date_format globally to the format you prefer, and then you can simply write ${x}.
(Also note that #assign is unnecessary above, as you can put arbitrarily complex expression inside ${}.)

Keyboard Input with Webshim's Date Picker

I am using the webshims library to support older browsers better with more modern features. While the date picker works great with the mouse I seem to be having problems using it from the keyboard. The easiest way to see this is visit the demo page. I am using Firefox since it doesn't have date support.
Without making any modifications try to type in a date. I can enter numbers but I cannot enter a "/". If you enable the placeholder it even suggests the slash. I tried leaving out the separator or using "-" (which it lets me type) but when the form submits I get no value.
How are you supposed to enter a date via the keyboard?
For bonus points is it possible to allow the date picker to not enforce a format? I have backend code that can parse a wide variety of date formats. So they can use the date picker if they wish but if they type something in then whatever they type in is sent onto the server without modification.
Try this.This works for '/' format..
$.webshims.formcfg = {
en: {
dFormat: '/',
dateSigns: '/',
patterns: {
d: "mm/dd/yy"
}
}
};
webshims.activeLang('en');
It appears that there is an issue with the locale settings. From what I can tell, there is a form config attribute called dateSigns that gets set in the locale settings.
The solution for me was to go to file shims/combos/5.js and look for a chunk of code having dateSigns in it. I found the relevant one for US English around line 1750, which looks like this:
if(!formcfg['en-US']){
formcfg['en-US'] = $.extend(true, {}, formcfg.en, {
date: {firstDay: 0},
patterns: {d: "mm/dd/yy"},
dateSigns: '-',
dFormat: "/",
meridian: ['AM', 'PM']
});
}
I updated the dateSigns line to
dateSigns: '/',
It is a horrible hack, and there must be a way to set this as a configuration, or at least get the real locale settings to handle this. But I didn't manage to in the limited time I have available. But maybe this will help you. It works for me.

Formatting Dates in Freemarker Where Date Type is Unknown

I have a Freemarker function whose aim is to print any value passed to it and am having difficulty handling dates in particular.
I understand that when Freemarker cannot determine what portion of a date is in use, that it will error when attempting to print the value directly, and so some special-casing is required for dates, but I've been unable to find a reliable workaround of this feature.
My function looks something like this:
<#function format value=''>
<#if value?is_date>
<#-- code to attempt to handle all types of date -->
<#else>
<#-- handle non-date values -->
</#if>
</#function>
So far, I have tried the following:
First attempt: just always print date and time; e.g. value?datetime
Problem: bombs if the value has already 'been told' it's date-only (e.g. format(value?date) - a usage I want to support)
Second attempt: attempt to print raw value using attempt/recover directives to handle problem cases; e.g.
<#attempt>
<#return value>
<#recover>
<#return value?datetime>
</#attempt>
Problem: the attempt/recover directives don't successful catch the exception - instead it's propagated out as before
I've tried many other things but the above approaches were the more sensible, and unfortunately neither were successful. There seems to be a catch-22: if the date-type is unknown I can only print by choosing an arbitrary type to apply to all date values, but if I attempt to apply that type to a known-type date, it will fail where the types don't match.
Is there any way to determine whether the date type of a value is known before trying to print the value? If so, I could use the ?datetime built in only when necessary.
Ideally, I could tell Freemarker to just print the full date where it's unable to determine the exact type, instead of bombing - but I'm not sure this is currently possible.
Update: In FreeMarker 2.3.21 you can use <#if value?is_date_like>${value?datetime_if_unknown}<#else>...
Yeah, there should exist something like ?is_unknown_type_date, but it doesn't... I'm an FM maintainer so I will add that in 2.3.21 (but don't hold your breath until that's released). Meanwhile, you can write a TemplateMethodModelEx that does just that. Implementing it trivial as you will see, how to make them accessible to templates is a bit underdocumented... One way is just doping the TemplateMethodModelEx into the data-model or into the "shared variable" set of the Configuration. Another is putting this into some of your commonly #import-ed or #included template like <#assign isUnknownTypeDate='com.example.IsUnknownTypeDateMethod'?new()>.
BTW, #recover works for me for this (using a nightly 2.3.21, but I don't remember that it was ever broken). But don't use it for this anyway, as it will log the error. #recover is for emergency situations only, not for normal program flow.
As of providing a default format for unknowns-type dates... I feel uneasy about it as then these issues won't be caught during development, and very few will care to use a different FM configuration for production than for development.

Change Magento decimal field format

I need to change Magento's default decimal format. I mean, when I save '1' to a decimal field, it becomes '10000.0000' with this '.0000' in the end.
I need to change it to another format, which uses ',' instead of '.' to separate decimal (and currency) numbers.
This is the Brazilian standard and it's not being used even after changing the store language. This change should be reflected mainly in the admin side.
Thanks a lot!
==Edited==
I haven't solved the problem yet. I'm using PT-BR (Brazilian Portuguese) as default language and it still using the wrong decimal character.
It seems Magento have some not-localized price formatting (I mean, hard-coded) in a few points of code. For example: magento\js\prototype\validation.js at line 426 have:
|| (!isNaN(parseNumber(v)) && /^\s*-?\d*(\,\d*)?\s*$/.test(v));
but instead it needs to be
|| (!isNaN(parseNumber(v)) && /^\s*-?\d*(\,\d*)?\s*$/.test(v));
to fit into PT-BR format (or other locales to).
Am I right? Does anybody could fix this issue?
if you want to check in admin area for this change
you go to in admin left bottom drop down
and select
Português (Portugal) / português (Portugal)
it will show you currency as you want. Also if you doesn't install you package go to
http://www.magentocommerce.com/translations/list/19
download your package and add it to your
locale folder and select from configuration for front end also
hope this will sure help you.
I've applied the following change to the file magento\js\prototype\validation.js (line 426):
|| (!isNaN(parseNumber(v)) && /^\s*-?\d*(\,\d*)?\s*$/.test(v));
and also, changed the file lib/Varien/Data/Form/Element/Abstract.php by adding the first if statement:
public function getEscapedValue($index=null)
{
$value = $this->getValue($index);
if(is_numeric($value)){
$value= number_format($value, 3, ",", ".");
}
...
this changes have solved the problem so far. Do you see any side-effect?
Comments are welcome! Thanks!
Newer versions of Magento are based on Zend Framework currency locale format so the best way to do this is to change the language.xml from the Zend directory, more information is on this great article.

Resources