Skip to content

Instantly share code, notes, and snippets.

@xabbuh
Created June 20, 2019 11:46
Show Gist options
  • Save xabbuh/b697bd89a938847954d0d172ed5309b2 to your computer and use it in GitHub Desktop.
Save xabbuh/b697bd89a938847954d0d172ed5309b2 to your computer and use it in GitHub Desktop.
<?php
namespace App\Form\Type;
use Money\Currencies\ISOCurrencies;
use Money\Currency;
use Money\Formatter\DecimalMoneyFormatter;
use Money\Parser\DecimalMoneyParser;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\CallbackTransformer;
class AmountType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addModelTransformer(new CallbackTransformer(
function ($form) {
$currencies = new ISOCurrencies();
$moneyFormatter = new DecimalMoneyFormatter($currencies);
return $moneyFormatter->format($form['amount']);
},
function ($form) {
$currency = new Currency('CHF');
$currencies = new ISOCurrencies();
$moneyParser = new DecimalMoneyParser($currencies);
return $moneyParser->parse(strval($form), $currency);
}
));
}
public function getParent()
{
return MoneyType::class;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment