在symfony中嵌套形式symfony(孩子的孩子)中的按钮

时间:2016-03-25 16:09:17

标签: php symfony

这是我使用的形式:

$form = $this->createForm(new NewsType(), $news)
            ->add('edit', SubmitType::class, array('label' => 'edit'))
            ->add('delete', SubmitType::class, array('label' => 'delete'))
            ->add('comments', CollectionType::class, array('entry_type'   => CommentType::class));

CommentType:

 public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('author', TextType::class)
        ->add('text', TextType::class)
        ->add('remove', SubmitType::class);
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Comment'));
}

是否可以从CommentType访问删除按钮,以便在单击时删除注释条目。一切都正确映射,我可以看到我的页面上显示的评论对象,但是当我使用$form->get('remove')时,我得到"Child "remove" does not exist."甚至可以这样做吗?

1 个答案:

答案 0 :(得分:0)

你需要访问一个盛大的孩子:

foreach ($form->get('comments') as $entry) {
    $toRemove = $entry->get('remove')-isClicked();
    // handle it ...
}

但要单独提交,您必须确保在视图中构建“完整”子表单:

{{ form_start(form) }}
{% for child in form %}
    {% if 'news_comments' == child.vars['full_name'] %}
        {{ form_start(child) }}
        {{ form_row(child) }}
        {{ form_end(child) }}
    {% else %}
        {{ form_row(child) }}
    {% endif %}
{% endfor %}
{{ form_end(form) %}

除了注意:

小心,您似乎使用symfony 2.8并更新了表单类型的FQCN,但是创建表单也需要它:

$form = $this->createForm(NewsType::class, $news)