【问题标题】:symfony2 form: how to save entity and how to add more then one entity to the same form?symfony2 表单:如何保存实体以及如何将多个实体添加到同一个表单?
【发布时间】:2015-02-13 17:58:09
【问题描述】:

我在实体类型类中有这个函数

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        //...other controls
        ->add('types', 'entity', array(
            'class' => 'MyApplicationBundle:Type',
            'property' => 'type',
            'expanded' => false,
            'multiple' => true))
        ->add('save', 'submit');
}

档案实体有一个类型属性,多对可能关系

/**
 * @ORM\ManyToMany(targetEntity="Type", mappedBy="archives")
 **/
private $types;

类型实体在另一边有档案属性

/**
 * @ORM\ManyToMany(targetEntity="Archive", inversedBy="types")
 * @ORM\JoinTable(name="types_archives")
 **/
private $archives;

使用多选控件正确显示表单,但我只能保存在存档表中,而不是 types_archives 表中。关于如何修复的任何想法? 另外,我可以在同一类型中添加多个实体吗?

谢谢

【问题讨论】:

    标签: symfony doctrine-orm formbuilder


    【解决方案1】:

    如果只有一侧的关系保存在数据库中,请尝试执行以下步骤:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            //...other controls
            ->add('types', 'entity', array(
                'class' => 'MyApplicationBundle:Type',
                // This makes form call setter method on related entity
                'by_reference' => false,
                'allow_add' => true,
                'allow_delete' => true,
                'property' => 'type',
                'expanded' => false,
                'multiple' => true))
            ->add('save', 'submit');
    }
    

    Archive实体中:

    public function addType(Type $type){
        $this->types[] = $type;
        $type->addArchive($this);
    }
    
    public function removeType(Type $type){
        $this->types->removeElement($type);
        $type->setArchive(null);
    }
    

    我希望这对您问题的第一部分有所帮助。

    对于第二部分,您可以使用collection 输入查看以下链接:

    http://symfony.com/doc/current/reference/forms/types/collection.html

    【讨论】:

    • 感谢您的回复。它适用于插入但不适用于更新。我的意思是,如果我第一次选择,例如 opt1 和 opt2,就可以了。如果稍后更新我只选择 opt3,我将保存 opt1、opt2 和 opt3。
    • 感谢您的帮助,它运行良好。我只需要在我的 Entity\Type 类中添加一个 setArchive 方法,我不知道为什么学说:generate:entities 没有创建它,反正现在可以了,非常感谢
    【解决方案2】:

    这里有一些我会给你的方向。 1. 要保存相关实体,例如,如果您正在使用学说,请尝试阅读有关“级联持久性”的内容。 2. 要在表单上有多个实体,请阅读“类组成”。您将设置为表单的“数据类”的复合对象将允许您包含多个实体对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-10
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      相关资源
      最近更新 更多