我建议为此构建一个自定义类型,例如ChoiceOrTextType
. 向这种类型添加选项(名为“choice”)和文本字段(名为“text”)。
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ChoiceOrTextType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('choice', 'choice', array(
'choices' => $options['choices'] + array('Other' => 'Other'),
'required' => false,
))
->add('text', 'text', array(
'required' => false,
))
->addModelTransformer(new ValueToChoiceOrTextTransformer($options['choices']))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setRequired(array('choices'));
$resolver->setAllowedTypes(array('choices' => 'array'));
}
}
正如您已经猜到的,您还需要一个数据转换器,这可能非常简单:
use Symfony\Component\Form\DataTransformerInterface;
class ValueToChoiceOrTextTransformer implements DataTransformerInterface
{
private $choices;
public function __construct(array $choices)
{
$this->choices = $choices;
}
public function transform($data)
{
if (in_array($data, $this->choices, true)) {
return array('choice' => $data, 'text' => null);
}
return array('choice' => 'Other', 'text' => $data);
}
public function reverseTransform($data)
{
if ('Other' === $data['choice']) {
return $data['text'];
}
return $data['choice'];
}
}
现在只使“菜单”字段成为该类型的字段。
$builder->add('menu', new ChoiceOrTextType(), array(
'choices' => array('Option 1' => 'Option 1', 'Option 2' => 'Option 2'),
'required' => false,
));