Symfony2, relation manyToMany in a Form

陌路散爱 提交于 2019-12-23 05:42:59

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/21737307/symfony2-relation-manytomany-in-a-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!