在symfony中以嵌套形式symfony(孩子的孩子)访问按钮
问题描述:
This is form i use:
$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'));
}
Is it possible to access remove button from CommentType so when its clicked to delete comment entry. Everything is mapped properly, i can see comment objects displayed on my page, but when i use $form->get('remove')
i get "Child "remove" does not exist."
Is it even possible to do this way?
答
You need to access a grand grand child doing:
foreach ($form->get('comments') as $entry) {
$toRemove = $entry->get('remove')-isClicked();
// handle it ...
}
But to submit it separately you must ensure that your building the "complete" child form in your view:
{{ 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) %}
Aside note:
be careful, you seem to use symfony 2.8 and to have updated the FQCN for the form types, but it's needed too for creating the form:
$form = $this->createForm(NewsType::class, $news)