4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Form\Extension\Core\Type
;
14 use Symfony\Component\Form\AbstractType
;
15 use Symfony\Component\Form\FormInterface
;
16 use Symfony\Component\Form\FormBuilderInterface
;
17 use Symfony\Component\Form\Extension\Core\DataTransformer\MoneyToLocalizedStringTransformer
;
18 use Symfony\Component\Form\FormView
;
19 use Symfony\Component\OptionsResolver\OptionsResolverInterface
;
21 class MoneyType
extends AbstractType
23 protected static $patterns = array();
28 public function buildForm(FormBuilderInterface
$builder, array $options)
31 ->addViewTransformer(new MoneyToLocalizedStringTransformer(
32 $options['precision'],
43 public function buildView(FormView
$view, FormInterface
$form, array $options)
45 $view->vars
['money_pattern'] = self
::getPattern($options['currency']);
51 public function setDefaultOptions(OptionsResolverInterface
$resolver)
53 $resolver->setDefaults(array(
65 public function getName()
71 * Returns the pattern for this locale
73 * The pattern contains the placeholder "{{ widget }}" where the HTML tag should
76 protected static function getPattern($currency)
79 return '{{ widget }}';
82 $locale = \Locale
::getDefault();
84 if (!isset(self
::$patterns[$locale])) {
85 self
::$patterns[$locale] = array();
88 if (!isset(self
::$patterns[$locale][$currency])) {
89 $format = new \
NumberFormatter($locale, \NumberFormatter
::CURRENCY
);
90 $pattern = $format->formatCurrency('123', $currency);
92 // the spacings between currency symbol and number are ignored, because
93 // a single space leads to better readability in combination with input
96 // the regex also considers non-break spaces (0xC2 or 0xA0 in UTF-8)
98 preg_match('/^([^\s\xc2\xa0]*)[\s\xc2\xa0]*123(?:[,.]0+)?[\s\xc2\xa0]*([^\s\xc2\xa0]*)$/u', $pattern, $matches);
100 if (!empty($matches[1])) {
101 self
::$patterns[$locale][$currency] = $matches[1].' {{ widget }}';
102 } elseif (!empty($matches[2])) {
103 self
::$patterns[$locale][$currency] = '{{ widget }} '.$matches[2];
105 self
::$patterns[$locale][$currency] = '{{ widget }}';
109 return self
::$patterns[$locale][$currency];