首页 文章

以symfony形式添加和删除实体

提问于
浏览
1

我有一个Doctrine实体Document,它与实体File具有双向oneToMany关系 . 因此,一个Document可以有许多File实体 .

现在我想制作一个symfony表单,我可以在其中添加和删除文档中的文件 . 我通过CollectionType设置了DocumentType中包含的FileType:

//DocumentType.php
$builder->add('files', Type\CollectionType::class, ['entry_type' => FileType::class])

//FileType.php
$builder->add('id', Type\HiddenType::class);

这样我就可以获得带有文件ID的隐藏字段 . 我现在想要通过JS禁用字段,如果应该从文档中删除文件 . 但我无法发送表单,因为我得到错误:

Could not determine access type for property "id".

它只是因为我想使用Field的id . 当然,我可以使用src或File的任何其他列来标识要删除的正确实体 .

但我希望,在symfony中有一个更好的方法可以解决这个问题吗?

这是我的实体映射:

AppBundle\Entity\File:
    type: entity
    table: files
    repositoryClass: AppBundle\Repository\FileRepository
    manyToOne:
        document:
            targetEntity: Document
            inversedBy: files
            joinColumn:
                onDelete: CASCADE

AppBundle\Entity\Document:
    type: entity
    table: documents
    repositoryClass: AppBundle\Repository\DocumentRepository
    oneToMany:
        files:
            targetEntity: File
            mappedBy: document

1 回答

  • 0

    这不是Symfony问题,你的 File 实体没有任何方法来设置 id 属性的值 . 当Symfony的表单数据映射器尝试使用 PropertyAccessor 将提交的ID映射到 File 实体时,会导致错误 .

    还有一件事,如果你想允许你的集合添加/删除条目,选项 allow_add / allow_delete 必须是 true . 您不需要向 FileType 添加任何标识字段,Symfony表单通过索引处理它,我猜...

    // DocumentType.php
    $builder->add('files', Type\CollectionType::class, [
        'entry_type' => FileType::class,
        'allow_add' => true,
        'allow_delete' => true
    ]);
    
    // FileType.php
    // Add fields you want to show up to end-user to edit.
    $builder
        ->add('name', Type\TextType::class)
        ->add('description', Type\TextareaType::class)
    ;
    

相关问题