-->

创建一个表单时,请使用条件语句(Use a conditional statement when c

2019-06-26 11:51发布

我想创造的Symfony 表单时使用条件语句。

我使用在一般的情况下选择小部件 。 如果用户选择选项“ 其他 ”,我想显示一个额外的文本框控件 。 我想这可以在JavaScript中完成,但我怎么能仍然从2只小部件数据持续到在我的实体相同的属性?

我有这个至今:

  $builder->add('menu', 'choice', array(
        'choices'   => array('Option 1' => 'Option 1', 'Other' => 'Other'),
        'required'  => false,
    ));
  //How to add text box if choice == Other ????

我刨使用DataTransfomer,但2只小部件?

Answer 1:

我建议建立一个自定义类型,例如ChoiceOrTextType 。 这种类型添加两个选择(命名为“选择”)和文本框(称为“文本”)。

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,
));


文章来源: Use a conditional statement when creating a form