问题描述:

I have this function in a entitytype class

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');

}

the archive entity has a type property, many to may relation

/**

* @ORM\ManyToMany(targetEntity="Type", mappedBy="archives")

**/

private $types;

the type entity has a archives property on the other side

/**

* @ORM\ManyToMany(targetEntity="Archive", inversedBy="types")

* @ORM\JoinTable(name="types_archives")

**/

private $archives;

the form is correctly displayed with a select multiple control but I'm only able to save in the archive table, not in the types_archives table. Any idea on how to fix?

also, can I add more then one entity to the same type?

thank you

网友答案:

If just one side of relations saved in database try to do following steps:

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');
}

in Archive entity:

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

public function removeType(Type $type){
    $this->types->removeElement($type);
    $type->setArchive(null);
}

I hope this helps about first part of your question.

For the second part you can use collection type check out following link:

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

网友答案:

Here are some directions that I would give you. 1. To save the related entities, try reading about "cascade persist" if you are using doctrine for example. 2. To have multiple entities on the form, read about "class composition". A composite object which you will set as the form's "data class" will allow you contain multiple entity objects.

相关阅读:
Top