我有一个 bool 字段,我已将其作为选择字段(是或否)放入表单中。
如果没有数据转换器,我会得到 0 或 1。
我添加了一个 View BooleanToStringTransformer (这似乎合理):
$builder
->add(
$builder->create('myBooleanField', 'choice', array(
'choices' => array(true => 'Yes', false => 'No'),
))
->addViewTransformer(new BooleanToStringTransformer('1'))
)
当我尝试显示表单时,我收到错误“Expected a Boolean.”。
我的字段在创建表单之前设置为 false。
我试图将其设置为模型转换器:表单已显示,但是当我提交时,我的字段被声明为无效。
我究竟做错了什么?
编辑:我现在几乎明白了。
array(true => 'Yes', false => 'No')
更改了我的选择列表至 array('yes' => 'Yes', 'no' => 'No')
所以代码现在看起来像
->addModelTransformer(new BooleanToStringTransformer('yes'))
数据转换有效,除了我的字段始终设置为 true,无论我选择什么值。
怎么了?
最佳答案
答案是:我不应该认为默认的 Symfony BooleanToStringDataTransformer 正在做这项工作。它为假值而不是字符串返回 null。
所以我创建了自己的数据转换器:
<?php
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
class BooleanToStringTransformer implements DataTransformerInterface
{
private $trueValue;
private $falseValue;
public function __construct($trueValue, $falseValue)
{
$this->trueValue = $trueValue;
$this->falseValue = $falseValue;
}
public function transform($value)
{
if (null === $value) {
return null;
}
if (!is_bool($value)) {
throw new TransformationFailedException('Expected a Boolean.');
}
return true === $value ? $this->trueValue : $this->falseValue;
}
public function reverseTransform($value)
{
if (null === $value) {
return null;
}
if (!is_string($value)) {
throw new TransformationFailedException('Expected a string.');
}
return $this->trueValue === $value;
}
}
关于forms - Symfony2 表单 BooleanToStringTransformer 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18528318/