【问题标题】:remove entity from entity form field if custom condition is matched如果匹配自定义条件,则从实体表单字段中删除实体
【发布时间】:2015-05-13 08:49:14
【问题描述】:

我有一个取消订阅表单,其中第一个字段是一个实体字段,用于获取我的 UnsubscribeType 实体:

$builder
    ->add('type', 'entity', array(
        'class' => 'Evo\SubscriptionBundle\Entity\UnsubscribeType',
        'property' => 'name',
        'label' => 'Choose process type',
        'empty_value'   => 'Choose an option',
        'empty_data' => null,
        'label_attr' => array(
            'class' => 'control-label',
        ),
        'attr' => array(
            'class' => 'form-control',
        ),
    ))

此集合包含 2 个实体,#1 和 #2。如果有关已验证用户的自定义测试失败,我想从选择字段中删除实体 #2。

假设我要测试$this->getUser()->getCustomField()。如果是false,那么我想从包含我的 UnsubscribeType 实体的选择字段中删除实体 #2。

知道怎么做吗?

【问题讨论】:

    标签: forms symfony entity


    【解决方案1】:

    也许您可以将控制器的测试结果传递给表单构建器,然后使用'property' => 'name' 或'choices => // fetch entity #1 here。

    所以,像这样

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if($options['customField'] === TRUE)
        {
            $builder
                ->add('type', 'entity', array(
                   'class' => 'Evo\SubscriptionBundle\Entity\UnsubscribeType',
                   'property' => 'name',
                   // ..
            ;
        }
        else
        {
            $builder
                ->add('type', 'entity', array(
                   'class' => 'Evo\SubscriptionBundle\Entity\UnsubscribeType',
                   'choices' => $options['customField'],
                   // ..
            ;
        }
    }
    
    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        // ..
    
        $resolver->setRequired(array(
            'customField'
        ));
    }
    

    在你的控制器中:

    $form = $this->get('form.factory')->create(new EntryType(), $entry, array(
            'customField' => $this->getUser()->getCustomField()
    ));
    

    getCustomField() 返回 true 或您希望填充选择字段的实体(或实体集合)。我的解决方案将涉及更改 getCustomField 方法,但不知道这是否适合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 2021-12-28
      相关资源
      最近更新 更多