IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Symfony PHP Discussion :

Object of class App\Entity\Category could not be converted to string + Slug défaillant


Sujet :

Symfony PHP

  1. #1
    Membre éprouvé
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    1 126
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Janvier 2011
    Messages : 1 126
    Par défaut Object of class App\Entity\Category could not be converted to string + Slug défaillant
    Bonjour à tous,

    1/ Suite à un changement de dossier et malgré avoir changé namespace et routes correctement l'erreur "Object of class App\Entity\Category could not be converted to string" apparaît seulement lorsque lesméthodes crud sont invoquées concernant un article, la liste des articles elle fonctionne... A noter que il existe une relation ManyToOne entre Articles et Catégories...

    J'ai essayé de rajouter __toString aux fonctions de l'entité Article.php mais une erreur de syntaxe apparaît (peut être parceque ce sont des fonctions nommées ?)

    2/ D'autre part le slug ne se constitue pas ni pour article ni pour category, géré pourtant avec Gedmo... que fais-je mal ?

    Merci d'avance pour vos aimables réponses

    Entité Article.php:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    <?php
     
    namespace App\Entity;
     
    use App\Repository\ArticleRepository;
    use Doctrine\DBAL\Types\Types;
    use Doctrine\ORM\Mapping as ORM;
    use Gedmo\Mapping\Annotation as Gedmo;
    use ApiPlatform\Metadata\ApiResource;
    use ApiPlatform\Metadata\GetCollection;
    use ApiPlatform\Metadata\Get;
     
    #[ORM\Entity(repositoryClass: ArticleRepository::class)]
    #[ApiResource(operations: [new Get(), new GetCollection()])]
     
    class Article
    {
        #[ORM\Id]
        #[ORM\GeneratedValue]
        #[ORM\Column]
        private ?int $id = null;
     
        #[ORM\Column(length: 255)]
        private ?string $title = null;
     
        #[ORM\Column(length: 255)]
        private ?string $description = null;
     
        #[ORM\Column(type: Types::TEXT)]
        private ?string $content = null;
     
     
        #[Gedmo\Timestampable(on: 'create')]
        #[ORM\Column(type: Types::DATETIME_MUTABLE)]
        private ?\DateTimeInterface $createdAt = null;
     
        #[Gedmo\Timestampable(on: 'update')]
        #[ORM\Column(type: Types::DATETIME_MUTABLE)]
        private ?\DateTimeInterface $updatedAt = null;
     
        #[ORM\Column(length: 255, nullable: true)]
        private ?string $image = null;
     
        #[Gedmo\Slug(fields: ["slug"])]
        #[ORM\Column(length: 255)]
        private ?string $slug = null;
     
        #[ORM\ManyToOne(inversedBy: 'articles')]
        private ?Category $category = null;
     
        public function getId(): ?int
        {
            return $this->id;
        }
     
        public function getTitle(): ?string
        {
            return $this->title;
        }
     
        public function setTitle(string $title): self
        {
            $this->title = $title;
     
            return $this;
        }
     
        public function getDescription(): ?string
        {
            return $this->description;
        }
     
        public function setDescription(string $description): self
        {
            $this->description = $description;
     
            return $this;
        }
     
        public function getContent(): ?string
        {
            return $this->content;
        }
     
        public function setContent(string $content): self
        {
            $this->content = $content;
     
            return $this;
        }
     
        public function getCreatedAt(): ?\DateTimeInterface
        {
            return $this->createdAt;
        }
     
        public function setCreatedAt(\DateTimeInterface $createdAt): self
        {
            $this->createdAt = $createdAt;
     
            return $this;
        }
     
        public function getUpdatedAt(): ?\DateTimeInterface
        {
            return $this->updatedAt;
        }
     
        public function setUpdatedAt(\DateTimeInterface $updatedAt): self
        {
            $this->updatedAt = $updatedAt;
     
            return $this;
        }
     
        public function getImage(): ?string
        {
            return $this->image;
        }
     
        public function setImage(?string $image): self
        {
            $this->image = $image;
     
            return $this;
        }
     
        public function getSlug(): ?string
        {
            return $this->slug;
        }
     
        public function setSlug(string $slug): self
        {
            $this->slug = $slug;
     
            return $this;
        }
     
        public function   getCategory(): ?Category
        {
            return $this->category;
        }
     
        public function setCategory(?Category $category): self
        {
            $this->category = $category;
     
            return $this;
        }
    }
    ArticleController:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    <?php
     
    namespace App\Controller\Admin;
     
    use App\Form\ArticleType;
    use App\Entity\Article;
    use App\Repository\ArticleRepository;
    use Doctrine\ORM\EntityManager;
    use Doctrine\ORM\EntityManagerInterface;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\Routing\Annotation\Route;
    use Symfony\Component\HttpFoundation\Request;
     
    class ArticleController extends AbstractController
    {
        /**
         * @Route("/admin/articles",name="articles_list")
         */
        public function articlesList(ArticleRepository $articleRepo)
        {
            //Afficher liste des articles en BDD
            $articles = $articleRepo->findAll();
     
            return $this->render("admin/article/articles.html.twig", ['articles' => $articles]);
        }
     
        /**
         * @Route("/admin/{id}/delete",name="article_delete")          
         */
        public function articleDelete($id, ArticleRepository $articleRepo, EntityManagerInterface $entitymanager)
        {
            $article = $articleRepo->find($id);
            $entitymanager->remove($article);
            $entitymanager->flush();
            return $this->redirectToRoute("articles_list");
        }
     
        /**
         *@Route("/admin/article/create",name="article_create")
         */
        public function articleCreate(Request $request, EntityManagerInterface $entityManager)
        {
            $article = new Article();
            $articleForm = $this->createForm(ArticleType::class, $article);
            $articleForm->handleRequest($request);
     
            if ($articleForm->isSubmitted() && $articleForm->isvalid()) {
                $entityManager->persist($article);
                $entityManager->flush();
            }
     
     
            return $this->render("admin/article/article_create.html.twig", ['articleForm' => $articleForm->createView()]);
        }
     
        /**
         * @Route("/admin/article/{id}/update",name="article_update")  
         */
        public function articleUpdate($id, Request $request, ArticleRepository $articleRepo, EntityManagerInterface $entityManager)
        {
            $article = $articleRepo->find($id);
            $articleForm = $this->createForm(ArticleType::class, $article);
            $articleForm->handleRequest($request);
     
            if ($articleForm->isSubmitted() && $articleForm->isvalid()) {
                $entityManager->persist($article);
                $entityManager->flush();
            }
            return $this->render("admin/article/article_create.html.twig", ['articleForm' => $articleForm->createView()]);
        }
    }
    Entité Category :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    <?php
     
    namespace App\Entity;
     
    use App\Repository\CategoryRepository;
    use Doctrine\Common\Collections\ArrayCollection;
    use Doctrine\Common\Collections\Collection;
    use Doctrine\DBAL\Types\Types;
    use Doctrine\ORM\Mapping as ORM;
    use Gedmo\Mapping\Annotation as Gedmo;
    use ApiPlatform\Metadata\ApiResource;
    use ApiPlatform\Metadata\GetCollection;
    use ApiPlatform\Metadata\Get;
     
    #[ORM\Entity(repositoryClass: CategoryRepository::class)]
    #[ApiResource(operations: [new Get(),new GetCollection()])]
     
    class Category
    {
        #[ORM\Id]
        #[ORM\GeneratedValue]
        #[ORM\Column]
        private ?int $id = null;
     
        #[ORM\Column(length: 255)]
        private ?string $title = null;
     
        #[ORM\Column(length: 255, nullable: true)]
        private ?string $description = null;
     
        #[ORM\Column(length: 255, nullable: true)]
        private ?string $color = null;
     
        #[Gedmo\Slug(fields: ["slug"])]
        #[ORM\Column(length: 255)]
        private ?string $slug = null;
     
        #[Gedmo\Timestampable(on: 'create')]
        #[ORM\Column(type: Types::DATETIME_MUTABLE)]
        private ?\DateTimeInterface $createdAt = null;
     
        #[Gedmo\Timestampable(on: 'update')]
        #[ORM\Column(type: Types::DATETIME_MUTABLE)]
        private ?\DateTimeInterface $updatedAt = null;
     
        #[ORM\OneToMany(mappedBy: 'category', targetEntity: Article::class)]
        private Collection $articles;
     
        public function __construct()
        {
            $this->articles = new ArrayCollection();
        }
     
        public function getId(): ?int
        {
            return $this->id;
        }
     
        public function getTitle(): ?string
        {
            return $this->title;
        }
     
        public function setTitle(string $title): self
        {
            $this->title = $title;
     
            return $this;
        }
     
        public function getDescription(): ?string
        {
            return $this->description;
        }
     
        public function setDescription(?string $description): self
        {
            $this->description = $description;
     
            return $this;
        }
     
        public function getColor(): ?string
        {
            return $this->color;
        }
     
        public function setColor(?string $color): self
        {
            $this->color = $color;
     
            return $this;
        }
     
        public function getSlug(): ?string
        {
            return $this->slug;
        }
     
        public function setSlug(string $slug): self
        {
            $this->slug = $slug;
     
            return $this;
        }
     
        public function getCreatedAt(): ?\DateTimeInterface
        {
            return $this->createdAt;
        }
     
        public function setCreatedAt(\DateTimeInterface $createdAt): self
        {
            $this->createdAt = $createdAt;
     
            return $this;
        }
     
        public function getUpdatedAt(): ?\DateTimeInterface
        {
            return $this->updatedAt;
        }
     
        public function setUpdatedAt(\DateTimeInterface $updatedAt): self
        {
            $this->updatedAt = $updatedAt;
     
            return $this;
        }
     
        /**
         * @return Collection<int, Article>
         */
        public function getArticles(): Collection
        {
            return $this->articles;
        }
     
        public function addArticle(Article $article): self
        {
            if (!$this->articles->contains($article)) {
                $this->articles->add($article);
                $article->setCategory($this);
            }
     
            return $this;
        }
     
        public function removeArticle(Article $article): self
        {
            if ($this->articles->removeElement($article)) {
                // set the owning side to null (unless already changed)
                if ($article->getCategory() === $this) {
                    $article->setCategory(null);
                }
            }
     
            return $this;
        }
    }
    CategoryController :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    <?php
     
    namespace App\Controller\Admin;
     
    use App\Entity\Category;
    use App\Form\CategoryType;
    use App\Repository\CategoryRepository;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\Routing\Annotation\Route;
     
    #[Route('/admin/categories')]
    class CategoryController extends AbstractController
    {
        #[Route('/', name: 'app_category_index', methods: ['GET'])]
        public function index(CategoryRepository $categoryRepository): Response
        {
            return $this->render('admin/category/index.html.twig', [
                'categories' => $categoryRepository->findAll(),
            ]);
        }
     
        #[Route('/new', name: 'app_category_new', methods: ['GET', 'POST'])]
        public function new(Request $request, CategoryRepository $categoryRepository): Response
        {
            $category = new Category();
            $form = $this->createForm(CategoryType::class, $category);
            $form->handleRequest($request);
     
            if ($form->isSubmitted() && $form->isValid()) {
                $categoryRepository->save($category, true);
     
                return $this->redirectToRoute('app_category_index', [], Response::HTTP_SEE_OTHER);
            }
     
            return $this->render('admin/category/new.html.twig', [
                'category' => $category,
                'form' => $form,
            ]);
        }
     
        #[Route('/{id}', name: 'app_category_show', methods: ['GET'])]
        public function show(Category $category): Response
        {
            return $this->render('admin/category/show.html.twig', [
                'category' => $category,
            ]);
        }
     
        #[Route('/{id}/edit', name: 'app_category_edit', methods: ['GET', 'POST'])]
        public function edit(Request $request, Category $category, CategoryRepository $categoryRepository): Response
        {
            $form = $this->createForm(CategoryType::class, $category);
            $form->handleRequest($request);
     
            if ($form->isSubmitted() && $form->isValid()) {
                $categoryRepository->save($category, true);
     
                return $this->redirectToRoute('app_category_index', [], Response::HTTP_SEE_OTHER);
            }
     
            return $this->render('admin/category/edit.html.twig', [
                'category' => $category,
                'form' => $form->createView(),
            ]);
        }
     
        #[Route('/{id}', name: 'app_category_delete', methods: ['POST'])]
        public function delete(Request $request, Category $category, CategoryRepository $categoryRepository): Response
        {
            if ($this->isCsrfTokenValid('delete'.$category->getId(), $request->request->get('_token'))) {
                $categoryRepository->remove($category, true);
            }
     
            return $this->redirectToRoute('app_category_index', [], Response::HTTP_SEE_OTHER);
        }
    }
    Article_create.html.twig:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <!DOCTYPE html>
    <html lang="fr">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Créer un article</title>
    </head>
    <body>
        {{form(articleForm)}}
    </body>
    </html>

  2. #2
    Membre confirmé
    Homme Profil pro
    Administrateur systèmes et réseaux
    Inscrit en
    Septembre 2013
    Messages
    71
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Gers (Midi Pyrénées)

    Informations professionnelles :
    Activité : Administrateur systèmes et réseaux
    Secteur : Santé

    Informations forums :
    Inscription : Septembre 2013
    Messages : 71
    Par défaut
    Bonjour,

    J'ignore si ça va vous aider mais comme ce n'est pas précisé... avez-vous pensée a vider le cache ?

    Pourriez-vous nous donner un peu plus d'information sur l'apparition de l'erreur "Object of class App\Entity\Category could not be converted to string" ? Sur quelle route elle apparait, est-il précisé le fichier ou la ligne sur laquelle cette erreur apparait, ...

  3. #3
    Membre éprouvé
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    1 126
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Janvier 2011
    Messages : 1 126
    Par défaut
    Bonjour Samche2000,

    J'ai réussi à avancer un peu :

    Il manquait à indiquer dans ArticleType.php (formBuilder) le OneToMany sur le champ category :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    ->add(
                    'category',
                    EntityType::class,
                    ['class' => Category::class, 'choice_label' => 'title']
                )
                ->add('Envoyer', SubmitType::class);
    Cependant, maintenant, apparaît une erreur "Class "App\Form\Category" does not exist" alors que ladite classe existe bien dans le dossier Entity...

    Si je renseigne les "use App\Entity\Category" apparait l'erreur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Class "app\Entity\Category" seems not to be a managed Doctrine entity. Did you forget to map it?
    pourtant elle est bien mappée dans l'entité Category.php :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
        #[ORM\OneToMany(mappedBy: 'category', targetEntity: Article::class)]
        private Collection $articles;
    Je sais que le problème vient de ladite relation car si je l'enlève le formulaire s'affiche correctement à nouveau ...

    Je ne pense pas avoir fait d'erreur de frappe... Deplus, j'ai vidé le cache, rien n'y fait...

Discussions similaires

  1. Réponses: 3
    Dernier message: 03/11/2008, 22h21
  2. Réponses: 2
    Dernier message: 14/02/2008, 17h21
  3. Réponses: 1
    Dernier message: 14/01/2008, 17h41
  4. [PEAR][Net_Traceroute] Object of class could not be converted to string
    Par nicoxweb dans le forum Bibliothèques et frameworks
    Réponses: 6
    Dernier message: 15/12/2007, 13h21
  5. [PEAR] Sigma: "Object of class PEAR_Error could not be converted to string"
    Par onet dans le forum Bibliothèques et frameworks
    Réponses: 2
    Dernier message: 04/09/2007, 14h31

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo