Sonata Admin Bundle One-to-Many关系不保存外国ID

时间:2013-06-07 22:11:56

标签: symfony sonata-admin

我对SonataAdminBunle与symfony 2.2结合有问题。 我有一个Project实体和一个ProjectImage实体,并指定这两者之间的一对多关系,如下所示:

class Project
{
    /**
     * @ORM\OneToMany(targetEntity="ProjectImage", mappedBy="project", cascade={"all"}, orphanRemoval=true)
     */
    private $images;
}

class ProjectImage
{

    /**
     * @ORM\ManyToOne(targetEntity="Project", inversedBy="images")
     * @ORM\JoinColumn(name="project_id", referencedColumnName="id")
     */
    private $project;
}

我已经配置了ProjectAdmin和ProjectImageAdmin:

class ProjectAdmin extends Admin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('title')
            ->add('website')
            ->add('description', 'textarea')
            ->add('year')
            ->add('tags')
            ->add('images', 'sonata_type_collection', array(
                            'by_reference' => false
            ), array(
                            'edit' => 'inline',
                            'inline' => 'table',
                            'sortable' => 'id',
            ))
            ;
    }
}

class ProjectImageAdmin extends Admin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('file', 'file', array(
                          'required' => false
            ))
            ;
    }
}

问题是在数据库的project_image表中没有保存project_id,而所有其他数据都是,并且图像也被保存。无法在其他地方找到合适的答案。

7 个答案:

答案 0 :(得分:23)

虽然不相关,但我会轻微调整你的一对多注释:

class Project
{
    /**
     * @ORM\OneToMany(targetEntity="ProjectImage", mappedBy="project", cascade={"persist"}, orphanRemoval=true)
     * @ORM\OrderBy({"id" = "ASC"})
     */
    private $images;
}

回到正轨,您的注释和Sonata Admin表单看起来很好,所以我很确定您在Project实体类中缺少其中一种方法:

public function __construct() {
    $this->images = new \Doctrine\Common\Collections\ArrayCollection();
}

public function setImages($images)
{
    if (count($images) > 0) {
        foreach ($images as $i) {
            $this->addImage($i);
        }
    }

    return $this;
}

public function addImage(\Acme\YourBundle\Entity\ProjectImage $image)
{
    $image->setProject($this);

    $this->images->add($image);
}

public function removeImage(\Acme\YourBundle\Entity\ProjectImage $image)
{
    $this->images->removeElement($image);
}

public function getImages()
{
    return $this->Images;
}

在您的Admin类中:

public function prePersist($project)
{
    $this->preUpdate($project);
}

public function preUpdate($project)
{
    $project->setImages($project->getImages());
}

答案 1 :(得分:8)

由于Symfony表单集合已经发生了一些变化,现在添加 addChild() removeChild()并将 by_reference 选项设置为< strong> false 自动保留Collection并按预期在反面设置ID。

这是一个完整的工作版本: https://gist.github.com/webdevilopers/1a01eb8c7a8290d0b951

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('childs', 'sonata_type_collection', array(
            'by_reference' => false
        ), array(
            'edit' => 'inline',
            'inline' => 'table'
        ))
    ;
}

addChild()方法必须包含子项父项的setter:

public function addChild($child)
{
    $child->setParent($this); // !important
    $this->childs[] = $child;
    return $this;
} 

答案 2 :(得分:2)

您可以直接在preUpdate函数

中执行此操作
    public function prePersist($societate)
{
    $this->preUpdate($societate);
}

public function preUpdate($societate)
{
    $conturi = $societate->getConturi();
    if (count($conturi) > 0) {
        foreach ($conturi as $cont) {
            $cont->setSocietate($societate);
        }
    }
}

答案 3 :(得分:1)

浏览此链接 http://sonata-project.org/bundles/doctrine-orm-admin/master/doc/reference/form_field_definition.html#advanced-usage-many-to-one 这个链接将帮助你很多关于奏鸣曲管理包中的关联映射。

答案 4 :(得分:0)

我解决的一种方法是通过自定义Sonata模型管理器手动设置所有反面关联。

<?php

namespace Sample\AdminBundle\Model;

class ModelManager extends \Sonata\DoctrineORMAdminBundle\Model\ModelManager
{
    /**
     * {@inheritdoc}
     */
    public function create($object)
    {
        try {
            $entityManager = $this->getEntityManager($object);
            $entityManager->persist($object);
            $entityManager->flush();
            $this->persistAssociations($object);
        } catch (\PDOException $e) {
            throw new ModelManagerException('', 0, $e);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function update($object)
    {       
        try {
            $entityManager = $this->getEntityManager($object);
            $entityManager->persist($object);
            $entityManager->flush();
            $this->persistAssociations($object);
        } catch (\PDOException $e) {
            throw new ModelManagerException('', 0, $e);
        }
    }

    /**
     * Persist owning side associations
     */
    public function persistAssociations($object)
    {       
        $associations = $this
            ->getMetadata(get_class($object))
            ->getAssociationMappings();

        if ($associations) {
            $entityManager = $this->getEntityManager($object);

            foreach ($associations as $field => $mapping) {
                if ($mapping['isOwningSide'] == false) {
                    if ($owningObjects = $object->{'get' . ucfirst($mapping['fieldName'])}()) {
                        foreach ($owningObjects as $owningObject) {
                            $owningObject->{'set' . ucfirst($mapping['mappedBy']) }($object);
                            $entityManager->persist($owningObject);
                        }
                        $entityManager->flush();
                    }
                }
            }
        }
    }
}

请务必在services.yml文件中将其定义为新服务:

services:
    sample.model.manager:
        class: Sample\AdminBundle\Model\ModelManager
        arguments: [@doctrine]


    sample.admin.business:
        class: Sample\AdminBundle\Admin\BusinessAdmin
        tags:
            - { name: sonata.admin, manager_type: orm, group: "Venues", label: "Venue" }
        arguments: [~, Sample\AppBundle\Entity\Business, ~]
        calls:
            - [ setContainer, [@service_container]]
            - [ setModelManager, [@sample.model.manager]]

答案 5 :(得分:0)

public function prePersist($user)
{
    $this->preUpdate($user);
}

public function preUpdate($user)
{
    $user->setProperties($user->getProperties());
}

这完全解决了我的问题,谢谢!

答案 6 :(得分:0)

最简单的解决方案是自然替换您的变量名;这对我有用: 'by_reference'=>假

如下:

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('name')
        ->add('articles', EntityType::class, array(
            'class' => 'EboxoneAdminBundle:Article',
            'required' => false,
            'by_reference' => false,
            'multiple' => true,
            'expanded' => false,
        ))
        ->add('formInputs', CollectionType::class, array(
            'entry_type' => FormInputType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'by_reference' => false,
        ))
    ;
}