【问题标题】:Symfony2.7, having problems with a form collections field and DoctrineSymfony2.7,表单集合字段和 Doctrine 存在问题
【发布时间】:2015-07-31 21:40:59
【问题描述】:

我有一个博客实体,它应该有一个投票实体,每个投票实体都有许多与之关联的选择实体。我试图为博客创建一个“添加/编辑投票”表单。在该表单中,除了投票表单字段之外,我还希望有一个允许您添加选项的字段(每个字段都有一个简单的文本字段)。我无法弄清楚我应该如何编写代码以使其正常工作。 PollType 表单如下所示:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('title', 'text');
    $builder->add('choices', 'collection', 
        array(
            'label_attr' => array(
                'style' => 'vertical-align: top;'
            ), 
            'type' => 'text', 
            'required' => false, 
            'allow_add' => true, 
            'allow_delete' => true, 
            'delete_empty' => true, 
            'attr' => array(
                'style' => 'display: inline-block; margin: 0 0 20px 20px; width: 200px;'
            )));
    $builder->add('description', 'textarea', array('attr' => array('rows' => 6)));
    $builder->add('save', 'submit', array('label' => 'Create Poll'));
    $builder->getForm();
}

最初我有 'type' => new ChoiceType() 与 ChoiceType 是:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('title', 'text');
}

但我不得不删除所有这些,因为我找不到任何解决方案的“bootstrap_3_layout.html.twig 中不存在变量“扩展””错误。我将类型更改为文本,但现在我很困惑如何从每个“选择”字段中收集数据,将其保存到 Choices 实体,并将所有这些数据与新的 Poll 相关联(这可能不是已插入,因此我没有要添加到 Choices->pollID 的 ID)。有没有一种标准的方法来做我错过的这种事情?

【问题讨论】:

    标签: php forms entity-framework symfony doctrine-orm


    【解决方案1】:

    如果你有 Poll 实体和 Choice 实体,那么它看起来像这样:

    $builder->add('choice', 'entity', array(
        'class' => 'AcmeHelloBundle:Choice',
        'query_builder' => function (EntityRepository $er) {
            return $er->createQueryBuilder('c')
                ->orderBy('choice.name', 'ASC');
        },
    ));
    

    您还必须与您的实体有 OneToMany 或 ManyToMany 关联。

    更多关于entity Field Type

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多