symfony CollectionType窗体需要错误的类型实体

6za6bjd0  于 2023-04-07  发布在  其他
关注(0)|答案(1)|浏览(127)

我尝试在数据库中呈现一个包含所有city(也就是“ville”)和邮政编码的表单,以便用户可以编辑任何内容或添加一个新城市。我使用CollectionType这样做,所以我可以只有一个大表单(按照documentations)。
下面是我的CitiesCollectionType:

use App\Entity\Ville;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class VillesCollectionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('villes',CollectionType::class, [
                'entry_type'=> VilleType::class,
                'entry_options'=>['label'=>false],
                'allow_add'=>true,
            ])

        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Ville::class,

        ]);
    }

我的VilleType

use App\Entity\Ville;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class VilleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('nom')
            ->add('codePostal')
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Ville::class,
        ]);
    }
}

我使用findAll()从我的控制器中的数据库中加载所有城市,我得到了一个城市数组。下面是我得到的错误:
表单的视图数据应该是“App\Entity\Ville”,但它是一个“array”。您可以通过将“data_class”选项设置为null或添加一个视图转换器来避免此错误,该转换器将“array”转换为“App\Entity\Ville”的示例。
我理解我的表单应该期望一个“ville”数组,我不明白为什么它期望一个单一的实体。

vwkv1x7d

vwkv1x7d1#

在第一个代码片段中,您使用了错误的类

$resolver->setDefaults([
   'data_class' => Ville::class,
]);

在这里你必须设置集合类

相关问题