我的Symfony3表单有问题。 我的ShippingType如下:
$builder
->add('name')
->add('price', TextType::class, [
'required' => false,
'empty_data' => 0
])
->add('url')
->add('tax', ChoiceType::class, [
'choices' => [
'0%' => 0,
'5%' => 5,
'8%' => 8,
'23%' => 23,
],
])
->add('free_delivery_level')
;
$builder
->get('price')
->addModelTransformer($this->priceTransformerShipping);
问题是我的运费为0时。Symfony仍将其转换为NULL值。转储表单数据时,会得到如下结果:
object(AppBundle \ Entity \ Shipping)#8397(6){[“ id”:protected] => NULL [“名称”:受保护的] =>字符串(4)“ asdg” [“价格”:受保护的] => NULL [“ url”:受保护] => NULL [“ tax”:受保护] => int(0) [“ free_delivery_level”:受保护] => NULL}
我还尝试将setPrice($ price)更改为此:
public function setPrice($price)
{
if(!$price){
$price = 0;
}
$this->price = $price;
}
但这也不起作用
我的价格转换器代码:
class PriceTransformerShipping implements DataTransformerInterface
{
public function transform($price)
{
if(is_null($price)){
return 0;
}
$price /= 100.0;
return number_format($price, 2, ',', '');
}
public function reverseTransform($value)
{
if(empty($value) || is_null($value)){
return null;
}
$price = str_replace(',', '.', $value);
return $price * 100;
}
}