Search code examples
symfonyentities

entities in different bundles


I'm using Symfony 2 and I have two entities in different bundles like:

//this class overrides fos_user class
//User\UserBundle\Entity\User
class User extends BaseUser
{
    //..

    /**
        * @ORM\OneToMany(targetEntity="News\AdminBundle\Entity\News", mappedBy="author_id")
        */
        protected $news_author;

    //...
}

//News\AdminBundle\Entity\News
class News
{
    //...

    /**
        * @ORM\ManyToOne(targetEntity="\User\UserBundle\Entity\User", inversedBy="news_author")
        * @ORM\JoinColumn(name="author_id", referencedColumnName="id")
        */
        protected $news_author;

    //...
}

Both classes (entities) works fine. I have successfully setup fos_user bundle with registration and other stuff. The same if for News class. Then I build relation between those two classes OneTo Many (User -> News) as it is shown in code. This also works fine without errors and I can add news that belongs to user. The problem is when I build a form with entity class like:

->add('year', 'entity', array(
    'class' => 'NewsAdminBundle:News',
    'query_builder' => function(EntityRepository $er) {
        return $er->createQueryBuilder('u')
                    ->groupBy('u.year')
                        ->orderBy('u.year', 'DESC');
         },))

This form shows me a years when news are posted (like archive). Years are showing fine, but when I submit (post) a form then I've got error:

Class User\UserBundle\Entity\News does not exist

I figure out that this error is connected with sentence

$form->bindRequest($request);

The problem is because I have two entities in different bundles. How can I solve this error?

Edit: I solved the problem. When I run

php app/console doctrine:generate:entities User
php app/console doctrine:generate:entities News

then Doctrine generate getters and setters in User and News. In entity News it generates method

/**
 * Add news_author
 *
 * @param User\UserBundle\Entity\News $newsAuthor
 */
public function addNews(User\UserBundle\Entity\News $newsAuthor)
{
    $this->news_author[] = $newsAuthor;
}

I was not paying attention to this method and I change it to this

/**
 * Add news_author
 *
 * @param News\AdminBundle\Entity\News $newsAuthor
 */
public function addNews(News\AdminBundle\Entity\News $newsAuthor)
{
    $this->news_author[] = $newsAuthor;
}

Now everything works fine. Thanks for all answers.


Solution

  •    /**
        * @ORM\ManyToOne(targetEntity="User\UserBundle\Entity\User", inversedBy="news_author")
        * @ORM\JoinColumn(name="author_id", referencedColumnName="id")
        */
        protected $news_author;
    

    You have to remove prefix backslash – see note in Doctrine documentation