Symfony2从欧元到美分
我有一个表格,我可以填写我的欧元,我的实体只知道美分,是一个整数。 所以我想创建(不确定是否使用了正确的方法)表单转换器 我所做的:Symfony2从欧元到美分,symfony,symfony-forms,Symfony,Symfony Forms,我有一个表格,我可以填写我的欧元,我的实体只知道美分,是一个整数。 所以我想创建(不确定是否使用了正确的方法)表单转换器 我所做的: class EuroTransformer implements DataTransformerInterface { public function transform($euro) { return $euro * 100; } public function reverseTransform($euro)
class EuroTransformer implements DataTransformerInterface
{
public function transform($euro)
{
return $euro * 100;
}
public function reverseTransform($euro)
{
return $euro / 100;
}
}
表格:
但我得到了下一个信息:
The form's view data is expected to be an instance of class Entity\InvoiceRule, but is a(n) integer. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) integer to an instance of Entity\InvoiceRule.
是的,我的默认选项中已经有一个data_类
如何解决我的问题
使用symfony2 2.2您需要在
reverseTransform
方法中返回一个对象:
/**
* @param int $cents
*
* @return InvoiceRule
*/
public function reverseTransform($cents)
{
$euro = new InvoiceRule();
$euro->setValue($cents / 100);
return $euro;
}
而您的转换
方法必须将对象转换为数字:
/**
* @param InvoiceRule $euro
*
* @return int
*/
public function transform($euro)
{
return $euro->getValue() * 100;
}
有关更多示例,请参见。您需要在
reverseTransform
方法中返回一个对象:
/**
* @param int $cents
*
* @return InvoiceRule
*/
public function reverseTransform($cents)
{
$euro = new InvoiceRule();
$euro->setValue($cents / 100);
return $euro;
}
而您的转换
方法必须将对象转换为数字:
/**
* @param InvoiceRule $euro
*
* @return int
*/
public function transform($euro)
{
return $euro->getValue() * 100;
}
有关更多示例,请参阅。Sf2 MoneyType处理此情况
->add('price', 'money', array(
'divisor' => 100,
'attr' => array(
'style' => 'width: 70px;'
)
))
Sf2 MoneyType处理这个案子
->add('price', 'money', array(
'divisor' => 100,
'attr' => array(
'style' => 'width: 70px;'
)
))
哦,他妈的多甜蜜啊!哦,真他妈的好甜!泰