【问题标题】:Add and delete entities in symfony form以 symfony 形式添加和删除实体
【发布时间】:2017-04-05 15:16:30
【问题描述】:

我有一个 Doctrine 实体文档,它与实体文件具有双向 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 的隐藏字段。如果应该从 Document 中删除文件,我现在想通过 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

【问题讨论】:

    标签: php forms symfony doctrine-orm


    【解决方案1】:

    这不是 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)
    ;
    

    【讨论】:

    • 谢谢,但是我怎样才能删除一个实体呢?当我不添加任何字段来更改其值时,如何标记应删除的实体?
    • 是的,您应该添加一些字段,例如我的示例 abow 以显示您的条目。您只需使用 javascript 将其删除,Symfony 表单将为您删除该条目。看看这个文档,它非常详细地介绍了 Symfony 表单集合:How to Embed a Collection of Forms
    • 我刚试过,添加一个字段,通过JS禁用它,检查它不在POST数据中,但symfony没有删除它。好的,我会再次检查您的文档页面。
    • 您确定allow_delete 选项是true 吗?您能否发布您的 DocumentFile 实体,以便我查看您如何删除您的引用。
    • 发布了他们的问题,也许这是一个问题,因为 Document 不是拥有方?我刚查了一下,表单提交没有调用Document的removeFile()方法
    猜你喜欢
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    相关资源
    最近更新 更多