Partage
  • Partager sur Facebook
  • Partager sur Twitter

Fixtures - cours Symfony2

Ajout adverts avec applications: call to member function

    19 octobre 2018 à 14:57:03

    Bonjour à tous, les codeurs de tous niveaux!

    Et particulièrement aux âmes généreuses ou à celles qui comme la mienne savent qu'expliquer aide à maîtriser!

    Je vous soumets mon problème.

    Bon, je perds mon temps car le tp concerne un système de purge que j'ai déjà réalisé à 90% et qui est fonctionnel, à part quelques détails à retoucher, ce n'est pas mon problème! Mais bon, j'apprends beaucoup dans mes digressions qui me mettent devant d'autres défis que ceux des cours, alors...

    Ce serait bien de pouvoir loader un chargement d'annonces et de candidatures pour faire des tests. Là je charge mes annonces avec Doctrine:Fixtures, pas de soucis. Mais il faut entrer manuellement dans MySqlAdmin les candidature après coup. Je me dis qu'il doit bien y avoir moyen.

    Bref, j'ai passé pas mal de temps à comprendre, tester et monter ce LoadAdvert pour mettre des annonces et intégrer ou non des candidatures.J'ai approfondi ma compréhension de la manière d'aller chercher des infos sur un tableau complexe et j'ai pondu une boucle for qui fait ce que j'espère faire! J'ai testé d'abord mon tableau et ma boucle for sur une page test.php  avec des echos et ça marche bien.

    Après, j'ai essayé de transposer tout cela dans la logique des fichiers load de DoctrineFixture.

    Voilà où j'en suis:
    <?php
    // src/OC/PlatformBundle/DataFixtures/ORM/LoadCategory.php
    
    namespace OC\PlatformBundle\DataFixtures\ORM;
    
    use Doctrine\Common\DataFixtures\FixtureInterface;
    use Doctrine\Common\Persistence\ObjectManager;
    use OC\PlatformBundle\Entity\Advert;
    use OC\PlatformBundle\Entity\Application;
    
    class LoadAdvert implements FixtureInterface
    {
      // Dans l'argument de la méthode load, l'objet $manager est l'EntityManager
      public function load(ObjectManager $manager)
      {
        // Liste des noms de catégorie à ajouter
        $listAdverts = array(
            array(
              array(
                'title'   => 'Recherche développeur frontend',
                'author'  => 'Alexandre',
                'content' => 'Nous recherchons un développeur Symfony débutant sur Lyon. Blabla…',
                'date'    => new \Datetime('2018-08-15 08:31:05'),
                'nb_applications' => '0'),
              array(
                    array(
                      'author'  => 'Marine',
                      'content' => 'J\'ai toutes les qualités requises.', 
                      'date'    => new \Datetime('2018-08-20 08:31:05')
                    ), 
                    array(
                      'author'  => 'Mathieu',
                      'content' => 'J\'ai tout ce qu\'il faut.', 
                      'date'    => new \Datetime('2018-08-22 10:31:05')
                    )
              )
            ),
            array(
              array(
                'title'   => 'Mission de webmaster',
                'author'  => 'Hugo',
                'content' => 'Nous recherchons un webmaster capable de maintenir notre site internet. …',
                'date'    => new \Datetime('2018-08-16 08:31:05'),
                'nb_applications' => '0'),
              array(
                array(), 
                array()
              )
            ),
            array(array(
              'title'   => 'Offre de stage webdesigner',
              'author'  => 'Mathieu',
              'content' => 'Nous proposons un poste pour webdesigner. Blabla…',
              'date'    => new \Datetime('2018-09-15 08:31:05'),
              'nb_applications' => '0'),
              array(
                array(
                'author'  => 'Mathieu',
                  'content' => 'J\'ai tout ce qu\'il faut.', 
                  'date'    => new \Datetime('2018-08-22 10:31:05')
                ), 
                array(              
                )
              )
            ),
            array(array(
              'title'   => 'Recherche développeur Symfony',
              'author'  => 'Gilbert',
              'content' => 'Nous recherchons un développeur Symfony débutant sur Québec. Blabla…',
              'date'    => new \Datetime('2018-09-31 08:31:05'),
              'nb_applications' => '0'),
              array(
                array(), 
                array()
              )
            )   
      );
    
    
        // foreach ($listAdverts as $adv) {
          // On crée la catégorie
      for ($a = 0; $a < 4; $a++)
      {
        $advert = new Advert();
        $advert->setTitle($listAdverts[$a][0]['title']);
        $advert->setAuthor($listAdverts[$a][0]['author']);
        $advert->setContent($listAdverts[$a][0]['content']);
        $advert->setDate($listAdverts[$a][0]['date']);
        $advert->setNbApplications($listAdverts[$a][0]['nb_applications']);
    
        // On la persiste
        $manager->persist($advert);
        $manager->flush();
    
        if (isset($listAdverts[$a][1][0]['author']))
        { 
          
          $application1 = new Application();
        
          $application1->setAuthor($listAdverts[$a][1][0]['author']);
          $application1->setDate($listAdverts[$a][1][0]['date']);
          $application1->setContent($listAdverts[$a][1][0]['content']);
        
          $manager->persist($application1);
    
          if (isset($listAdverts[$a][1][1]['author']))
          {
            $application2 =new Application();
            $application2->setAuthor($listAdverts[$a][1][1]['author']);
            $application2->setDate($listAdverts[$a][1][1]['date']);
            $application2->setContent($listAdverts[$a][1][1]['content']);
            $manager->persist($advert);
            $manager->persist($application2);
         
         }
         $manager->persist($advert);
        }
      }
    
        // On déclenche l'enregistrement de toutes les catégories
        $manager->flush();
      }
    }
    


    C'est peut-être un load trop complexe.

    Je ne sais pas trop pourquoi, mais ça plante avec cette erreur:

    Call to a member function increaseApplication() on null in E:\wamp64\www\Tp3ePartie\src\OC\PlatformBundle\Entity\Application.php on line 53
    [2018-10-19 11:21:35] php.CRITICAL: Fatal Error: Call to a member function increaseApplication() on null {"type":1,"file":"E:\\wamp64\\www\\Tp3ePartie\\src\\OC\\PlatformBundle\\Entity\\Application.php","line":53,"level":32767,"stack":[]}

    Je suis un peu dans un cul-de-sac, je manque de compréhension ou d'informations et je ne trouve pas dans mes recherches.

    Je comprends vaguement que le problème doit venir du fait que l'entité Advert ne serait pas tout à fait là. Ainsi, la fonction "PrePersist" increase() dans Application qui appelle celle de l'entité advert  planterait parce qu'on ne peut accéder (peut-etre) à Advert. On est en chargement en bdd des entités, elle n'y sont pas encore, alors ça se comprendrait...

    Pourtant il est instancié, mais évidemment, il n'avait pas été flushé, donc n'existait pas en bdd. Voilà pourquoi j'ai flushé l'entité Advert au milieu du load après avoir persisté les données d'advert(dans la boucle, oui je sais on ne flushe normalement pas dans une boucle!), espérant que ça changerait l'erreur. Que dalle!

    Normalement l'entrée d'une candidature doit se faire dans le contexte où l'on doit aller chercher une annonce bien en règle qu'on est allé récupéré dans le «dépôt» (je traduis!) et là ça doit aller comme sur des roulettes. Enfin, je n'ai pas encore fait les formulaires et tout ce que j'ai c'est un exemple donnée en dure dans la fonction addAction (ici) dans le cours pour montrer les requêtes dans le stack que ça générait, mais qui ne fonctionnait pas vraiment car on n'avait pas réglé la question des mails. L'exemple est antérieur à l'introduction du fameux PrePersist increase() qui plante, bref, ça ne m'avance pas!

    Bref, je mets mes deux entités associées à la question et espère vos lumières!

    <?php
    
    namespace OC\PlatformBundle\Entity;
    
    use Doctrine\Common\Collections\ArrayCollection;
    use Doctrine\ORM\Mapping as ORM;
    // N'oubliez pas ce use :
    use Gedmo\Mapping\Annotation as Gedmo;
    
    /**
     * @ORM\Table(name="oc_advert")
     * @ORM\Entity(repositoryClass="OC\PlatformBundle\Repository\AdvertRepository")
     * @ORM\HasLifecycleCallbacks()
     */
    class Advert
    {
      /**
       * @var int
       *
       * @ORM\Column(name="id", type="integer")
       * @ORM\Id
       * @ORM\GeneratedValue(strategy="AUTO")
       */
      private $id;
    
      /**
       * @var \DateTime
       *
       * @ORM\Column(name="date", type="datetime")
       */
      private $date;
    
      /**
       * @var string
       *
       * @ORM\Column(name="title", type="string", length=255)
       */
      private $title;
    
      /**
       * @var string
       *
       * @ORM\Column(name="author", type="string", length=255)
       */
      private $author;
    
      /**
       * @var string
       *
       * @ORM\Column(name="content", type="string", length=255)
       */
      private $content;
    
      /**
       * @ORM\Column(name="published", type="boolean")
       */
      private $published = true;
    
      /**
       * @ORM\OneToOne(targetEntity="OC\PlatformBundle\Entity\Image", cascade={"persist"})
       */
      private $image;
    
      /**
       * @ORM\ManyToMany(targetEntity="OC\PlatformBundle\Entity\Category", cascade={"persist"})
       * @ORM\JoinTable(name="oc_advert_category")
       */
      private $categories;
    
      /**
       * @ORM\OneToMany(targetEntity="OC\PlatformBundle\Entity\Application", mappedBy="advert", cascade={"remove"})
       */
      private $applications; // Notez le « s », une annonce est liée à plusieurs candidatures
    
      /**
       * @ORM\Column(name="updated_at", type="datetime", nullable=true)
       */
      private $updatedAt;
    
      /**
       * @ORM\Column(name="nb_applications", type="integer")
       */
      private $nbApplications = 0;
    
      /**
       * @Gedmo\Slug(fields={"title"})
       * @ORM\Column(name="slug", type="string", length=255, unique=true)
       */
      private $slug;
    
      public function __construct()
      {
        $this->date         = new \Datetime();
        $this->categories   = new ArrayCollection();
        $this->applications = new ArrayCollection();
      }
    
      /**
       * @ORM\PreUpdate
       */
      public function updateDate()
      {
        $this->setUpdatedAt(new \Datetime());
      }
    
      public function increaseApplication()
      {
        $this->nbApplications++;
      }
    
      public function decreaseApplication()
      {
        $this->nbApplications--;
      }
    
      /**
       * @return int
       */
      public function getId()
      {
        return $this->id;
      }
    
      /**
       * @param \DateTime $date
       */
      public function setDate($date)
      {
        $this->date = $date;
      }
    
      /**
       * @return \DateTime
       */
      public function getDate()
      {
        return $this->date;
      }
    
      /**
       * @param string $title
       */
      public function setTitle($title)
      {
        $this->title = $title;
      }
    
      /**
       * @return string
       */
      public function getTitle()
      {
        return $this->title;
      }
    
      /**
       * @param string $author
       */
      public function setAuthor($author)
      {
        $this->author = $author;
      }
    
      /**
       * @return string
       */
      public function getAuthor()
      {
        return $this->author;
      }
    
      /**
       * @param string $content
       */
      public function setContent($content)
      {
        $this->content = $content;
      }
    
      /**
       * @return string
       */
      public function getContent()
      {
        return $this->content;
      }
    
      /**
       * @param bool $published
       */
      public function setPublished($published)
      {
        $this->published = $published;
      }
    
      /**
       * @return bool
       */
      public function getPublished()
      {
        return $this->published;
      }
    
      public function setImage(Image $image = null)
      {
        $this->image = $image;
      }
    
      public function getImage()
      {
        return $this->image;
      }
    
      /**
       * @param Category $category
       */
      public function addCategory(Category $category)
      {
        $this->categories[] = $category;
      }
    
      /**
       * @param Category $category
       */
      public function removeCategory(Category $category)
      {
        $this->categories->removeElement($category);
      }
    
      /**
       * @return ArrayCollection
       */
      public function getCategories()
      {
        return $this->categories;
      }
    
      /**
       * @param Application $application
       */
      public function addApplication(Application $application)
      {
        $this->applications[] = $application;
    
        // On lie l'annonce à la candidature
        $application->setAdvert($this);
      }
    
      /**
       * @param Application $application
       */
      public function removeApplication(Application $application)
      {
        $this->applications->removeElement($application);
      }
    
      /**
       * @return \Doctrine\Common\Collections\Collection
       */
      public function getApplications()
      {
        return $this->applications;
      }
    
      /**
       * @param \DateTime $updatedAt
       */
      public function setUpdatedAt(\Datetime $updatedAt = null)
      {
          $this->updatedAt = $updatedAt;
      }
    
      /**
       * @return \DateTime
       */
      public function getUpdatedAt()
      {
          return $this->updatedAt;
      }
    
      /**
       * @param integer $nbApplications
       */
      public function setNbApplications($nbApplications)
      {
          $this->nbApplications = $nbApplications;
      }
    
      /**
       * @return integer
       */
      public function getNbApplications()
      {
          return $this->nbApplications;
      }
    
      /**
       * @param string $slug
       */
      public function setSlug($slug)
      {
          $this->slug = $slug;
      }
    
      /**
       * @return string
       */
      public function getSlug()
      {
          return $this->slug;
      }
    }
    
    <?php
    // src/OC/PlatformBundle/Entity/Application.php
    
    namespace OC\PlatformBundle\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * @ORM\Table(name="oc_application")
     * @ORM\Entity(repositoryClass="OC\PlatformBundle\Repository\ApplicationRepository")
     * @ORM\HasLifecycleCallbacks()
     */
    class Application
    {
      /**
       * @ORM\Column(name="id", type="integer")
       * @ORM\Id
       * @ORM\GeneratedValue(strategy="AUTO")
       */
      private $id;
    
      /**
       * @ORM\Column(name="author", type="string", length=255)
       */
      private $author;
    
      /**
       * @ORM\Column(name="content", type="text")
       */
      private $content;
    
      /**
       * @ORM\Column(name="date", type="datetime")
       */
      private $date;
    
      /**
       * @ORM\ManyToOne(targetEntity="OC\PlatformBundle\Entity\Advert", inversedBy="applications", cascade={"remove"})
       * @ORM\JoinColumn(nullable=false)
       */
      private $advert;
    
      public function __construct()
      {
        $this->date = new \Datetime();
      }
    
      /**
       * @ORM\PrePersist
       */
      public function increase()
      {
        $this->getAdvert()->increaseApplication();
      }
    
      /**
       * @ORM\PreRemove
       */
      public function decrease()
      {
        $this->getAdvert()->decreaseApplication();
      }
    
      /**
       * @return int
       */
      public function getId()
      {
        return $this->id;
      }
    
      /**
       * @param string $author
       */
      public function setAuthor($author)
      {
        $this->author = $author;
      }
    
      /**
       * @return string
       */
      public function getAuthor()
      {
        return $this->author;
      }
    
      /**
       * @param string $content
       */
      public function setContent($content)
      {
        $this->content = $content;
      }
    
      /**
       * @return string
       */
      public function getContent()
      {
        return $this->content;
      }
    
      /**
       * @param \Datetime $date
       */
      public function setDate(\Datetime $date)
      {
        $this->date = $date;
      }
    
      /**
       * @return \Datetime
       */
      public function getDate()
      {
        return $this->date;
      }
    
      /**
       * @param Advert $advert
       */
      public function setAdvert(Advert $advert)
      {
        $this->advert = $advert;
      }
    
      /**
       * @return Advert
       */
      public function getAdvert()
      {
        return $this->advert;
      }
    }
    

    Mille mercis d'avance!

    • Partager sur Facebook
    • Partager sur Twitter
    Francis du Canada - Soyons audacieux!

    Fixtures - cours Symfony2

    × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
    × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
    • Editeur
    • Markdown