2
votes

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.

1
How do you insert the category in the db? Are doctrine fixture also?Matteo
Yes, I insert it as a fixture. In order to load categories first, in my LoadCategory.php, I put > public function getOrder() { return 1; } And in my LoadSport.php, I put > public function getOrder() { return 2; }Nadjib
@Nadjib - You won't stop getting that error unless you do what I've written below. It is very simple.BentCoder

1 Answers

4
votes

Use the ObjectManager passed into the load function. Like so:

$category = $manager->getRepository('MyBundle:Category')->findOneById(1);

Update:

As pointed out below, whilst this approach is nice and simple it can lead to problems when manipulating data in the fixtures. The Symfony Docs details the correct way to do this.