我是 Symfony 4 的新手,我正在尝试使用带有数字选项的 ChoiceType 字段来呈现表单,以便生成用户选择的确切标签数。
这是我的 Controller :
class ContactController extends AbstractController
{
/**
* @Route("/matrix", name="matrix")
*/
public function index(Request $request)
{
$contact = new Contact();
// i've already added some tags
$tag3 = new Tag();
$tag3->setName('tag3');
$contact->getTags()->add($tag3);
$tag4=new Tag();
$tag4->setName('ciao');
$contact->getTags()->add($tag4);
$form = $this->createForm(ContactType::class, $contact);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$contactFormData = $form->getData();
dump($contactFormData);
}
return $this->render('contact/index.html.twig', array(
//'our_form' => $form,
'form' => $form->createView(),
));
}
在我的代码的这一点上,表格似乎已填写,我已经检查了一些转储。
这是我的 Twig
{% block body %}
<div>
{{ form_start(form) }}
{{ form_widget(form) }}
<ul class="tags" data-prototype="{{ form_widget(form.tags.vars.prototype)|e('html_attr') }}">
{% for tag in form.tags %}
<li> {{ form_row(tag.name) }}
</li>
{% endfor %}
</ul>
<input type="submit" value="Send" class="btn btn-success" />
{{ form_end(form) }}
</div>
{% endblock %}
看起来这两个文件之间没有可见性,实际上,他是无法进入for循环的。我已经丢弃了一些东西,我已经看到标签此时没有 child ,但它应该。
class ContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('motto')
->add('expectations', ChoiceType::class, array(
'choices' => array(
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5',
),
));
$builder->add('tags', CollectionType::class, array(
'entry_type' => TagType::class,
'entry_options' => array('label' => false),
'allow_add' => true,
'by_reference' => false,
'mapped' => false,
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
// Configure your form options here
]);
}
}
最佳答案
我对这段代码感到困惑 => $contact->getTags()->add($tag3);
。似乎 Tags
是一个实体,而 Contact
是另一个实体,所以你的 Contact
实体应该有 adders
/ removers
和/或 setters
/removers
(如果不需要累积两者则事件)。
因此您的实体应该喜欢:
class Contact
{
// ...
/** @var Collection */
protected $tag;
// ...
public function __construct()
{
$this->tags = new ArrayCollection();
}
// ...
public function addTag(Tag $tag)
{
$this->tags->add($tag);
}
public function removeTag(Tag $tag)
{
// ...
}
}
一个很好的例子来实现你的案例:How to Embed a Collection of Forms
然后我不知道你的 TagType 形式是什么样的,但即使它发展得很好,你的 Twig 也不行。
首先form_widget(form)
渲染整个表单
来自 Symfony 文档
Renders the HTML widget of a given field. If you apply this to an entire form or collection of fields, each underlying form row will be rendered.
所以重新渲染集合不会有任何效果。即使您的 Twig 代码不适合呈现集合。
关于php - 带有原型(prototype)的 Symfony 4 表单集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50814853/