Symfony2, relation manyToMany in a Form

2019-06-13 07:48发布

I start learning sf2, pretty cool, for my problem I have two tables:

Media

/**
 * @ORM\ManyToMany(targetEntity="Test\SiteBundle\Entity\Website", inversedBy="medias")
 * @ORM\JoinTable(name="media_website")

private $websites;

and Website

/**
 * @ORM\ManyToMany(targetEntity="Test\SiteBundle\Entity\Media", mappedBy="websites")

private $medias;

In my MediaType.php I have this:

$builder
        ->add('title')
        ->add('website', 'entity', array(
            'class'         =>  'TestSiteBundle:Website',
            'property'  =>  'name',
            'query_builder' => function(WebsiteRepository $er)use($user_id) {
                               return $er->getMyWebsites($user_id);
             },
            'multiple'=>false))

finally, in the twig page I have this:

<div class="form-group">
   {{ form_label(form.description, "Description", { 'label_attr': {'class': 'control-label col-md-2'} }) }}
   <div class="col-md-5">
        {{ form_widget(form.description, { 'attr': {'class': 'form-control'} }) }}
   </div>
</div>

When I try to add a Media I have this error:

Neither the property "websites" nor one of the methods "setWebsites()", "__set()" or "__call()" exist and have public access in class "Test\SiteBundle\Entity\Media". 

Any help ? and many thanks to you.

2条回答
够拽才男人
2楼-- · 2019-06-13 08:24

I found it, for persons who have the same problem, in the relation ManyToMany you need to have multiple=>true in your FormType, so my MediaType should be:

$builder

        ->add('websites', 'entity', array(
            'class'         =>  'EveadSiteBundle:Website',
            'property'  =>  'name',
            'query_builder' => function(WebsiteRepository $er)use($user_id) {
                               return $er->getMyWebsites($user_id);
             },
            'multiple'=>true))
查看更多
贪生不怕死
3楼-- · 2019-06-13 08:34

Set the properties on both classes to protected rather than private to allow doctrine to access them in its Proxy classes.

You'll also need to add public getter and setter methods in order to access the data on your models in your application. You can use the Symfony Console's doctrine:generate:entities command - see documentation here

查看更多
登录 后发表回答