Symfony 5.1嵌套表单与ArrayCollection



我有一个雇员实体、一个社团实体和一个站点实体,

一个社团可以有几个网站(OneToMany),员工有一个表单。在里面,我们有社会的选择。

我想把Site FormType嵌套在社会中。所以当我在EmployeeForm下选择一个社团时,它只会推荐与社团相关的网站。希望我讲清楚了。我遵循symfony文档,学习如何嵌入ArrayCollection。

https://symfony.com/doc/5.1/form/form_collections.html我看了https://symfony.com/doc/current/form/data_transformers.html

我不确定哪一个是最好的方法?

我仍然得到错误

类DoctrineORMPersistentCollection的对象不能是转换为字符串

,我无法在SocietyForm中隔离"名称";属性。我不想要一个集合,而是一个name (string)的列表。


EmployeeType

class EmployeeType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', NULL, [
'label' => 'Nom',
])
->add('firstname', NULL, [
'label' => 'Prénom',
])
->add('societe', EntityType::class, [
'label' => 'Société',
'class' => RefSociety::class,
'choice_label' => 'Name',
])
->add('site', EntityType::class, [
'label' => 'Site',
'class' => RefSociety::class,
'choice_label' => 'refSites'
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Employee::class,
]);
}
}

RefSocietyType

class RefSocietyType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('Name', NULL, [
'label' => 'Nom de société'
])
->add('refSites', CollectionType::class, array(
'type' => RefSiteType::class,
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false,
))   
->add('Adress', NULL, [
'label' => 'Adresse'
])
->add('PostalCode', NULL, [
'label' => 'Code postal'
])
->add('Country', NULL, [
'label' => 'Pays'
])
->add('City', NULL, [
'label' => 'Ville'
])
->add('save', SubmitType::class, [
'attr' => ['class' => 'btn btn-primary btn-block btn-radius'],
'label' => 'Sauvegarder'
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => RefSociety::class,
]);
}
}

RefSiteType

class RefSiteType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => RefSite::class,
]);
}
}

index.html.twig

{ form_start(employeeForm) }}
{{form_row(employeeForm.name, {'attr' : {'class' : ""} }) }}
{{form_row(employeeForm.firstname, {'attr' : {'class' : ""} }) }}
{{form_row(employeeForm.societe) }}
<ul class="sites">
{% for site in employeeForm.refSites %}
<li>{{ form_row(site.name) }}</li>
{% endfor %}
</ul>
{{ form_end(employeeForm) }}
->add('site', EntityType::class, [
'label' => 'Site',
'class' => RefSociety::class,
'choice_label' => 'refSites'
])

'choice_label' => 'refSites'表示方法getRefSites()被PropertyAccessor调用以获取标签名称,因此方法getRefSites返回集合(因为一个对多个),但标签必须是字符串。

也许你应该使用'choice_label' => 'name'?

相关内容

  • 没有找到相关文章

最新更新