0

I am developing a multi country multi language application and one of the issues I have are the decimal point separator and the date format. I am aware of the setLocale method, but the only changes I have seen are in translations. Do I have to use PHP's built in setlocale method to format the number and date correctly or is there another way?

Also, numbers (money) are stored in database MySQL, should I use a datatransformer at the form fields with using the locale or will they be handled automatically by symfony?

Emii Khaos
  • 9,983
  • 3
  • 34
  • 57
mentalic
  • 965
  • 2
  • 14
  • 30

3 Answers3

2

Check out the Twig International extension

For number format there is number_format however you may have to build your own extension to use NumberFormatter

Kris
  • 6,094
  • 2
  • 31
  • 46
2

I recommend to create custom Twig Extension with PHP intl. You can take a look into my answer to similar question.

namespace Acme\Bundle\DemoBundle\Twig;

class IntlExtension extends \Twig_Extension
{

    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('intl_day', array($this, 'intlDay')),
            new \Twig_SimpleFilter('intl_number', array($this, 'intlNumber')),
        );
    }

    // Other methods…

    /**
     * NULL locale cause load locale from php.ini
     */
    public function intlNumber($number, $locale = NULL)
    {
        $fmt = new \NumberFormatter($locale, \NumberFormatter::DECIMAL);
        return $fmt->format($number);
    }

    public function getName()
    {
        return 'intl_extension';
    }
}

Then in your Twig template you can use:

{{ entity.number_value|intl_number(app.request.locale) }} 

or if you use Symfony < 2.1 app.session.locale

Community
  • 1
  • 1
jkucharovic
  • 4,214
  • 1
  • 31
  • 46
0

Numbers and Money in forms

For numbers and money in form fields symfony has already a number and a money form type which handles the decimal point and grouping depending on the locale.

Number and Date formatting on output

Normally you format a date (in twig) with the date filter like mydate|date("m/d/Y") But you can set it for the complete twig environment, so you only have to call mydate|date. But this is only recommended, if the locale requirements are static for the complete application and not dynamically based on the users locale. For this you should consider a twig extension which @jkucharovic and @Kris have posted.

Emii Khaos
  • 9,983
  • 3
  • 34
  • 57
  • This is bad solution. For each request will be wasted system resources by doing unnecessary job – new listener injecting Twig and overwriting default formates – even if it wouldn't be used. Much better solution (and also less demanding) is create custom Twig extension and call it only if it is needed. – jkucharovic Jul 04 '13 at 05:12
  • 1
    yep, removed the listener and added a hint to you post. – Emii Khaos Jul 04 '13 at 17:07