I have two fixtures, one LoadSport.php and one LoadCategory.php in my Symfony project.
Every instance of sport has a private 'category' attribute which is an instance of Category. I am trying to retrieve the categories I already in my database and load them in the Sports fixture (I chose some sports). I followed the official using container within fixtures (http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html#using-the-container-in-the-fixtures) as suggested in another thread.
So this is my code for the LoadSport.php:
class LoadSport implements FixtureInterface, ContainerAwareInterface
{
private $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function load(ObjectManager $manager)
{
$i = 0;
$em = $this->container->get('doctrine')->getManager();
$category = $em->getRepository("MyBundle:Category")->findOneById(1);
$names = array('SportA', 'SportB', 'SportC');
foreach($names as $name)
{
$sport = new Sport();
$sport->setName($name);
$sport->setCategory($category);
$manager->persist($sport);
}
$manager->flush();
}
public function getOrder()
{
return 2;
}
I tried to call a separate manager to get Category n1, and when I do php app/console doctrine:fixture:load, I get this error message:
[Symfony\Component\Debug\Exception\ContextErrorException] Catchable Fatal Error: Argument 1 passed to MyBundle\Entity\Sport::setCategory() must be an instance of MyBundle\Entity\Category, null given, called in .../MyBundle/DataFixtures/ORM/LoadSport.php on line xx and defined
How can I retrieve the category of id 1. or any other category within my LoadSport.php fixture and set the category of the Sport instance? What am I doing wrong? Why am I getting a null value wheras as it should be a category entity?
Many thanks in advance.