Cannot autowire argument $blog of "App\Controller\BlogController::edit()": it references class "App\Entity\Blog" but no such service exists

Viewed 446

Here I'm trying to edit the post but it shows this autowire error.....even everything seems to be right in the codes......

enter image description here


here is the controller file with edit function which i used to edit my symfony project....i don't think there is any syntax error......its seems to be like something else

src/Controller/BlogController.php

 
<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Annotation;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\File\UploadedFile;

use Symfony\Component\DependencyInjection;

use App\Repository\BlogRepository;
use App\Entity\Blog;
use App\Form\BlogType;


class BlogController extends AbstractController
{
 /**
    * @Route("/{id}/edit", name="edit", methods={"GET","POST"})
    * @param Request $request
    * @param Blog $blog
    * @return Response
    */
    public function edit(Request $request, Blog $blog, $id): Response
    {          
        $form = $this->createForm(BlogType::class, $blog);
        $form->handleRequest($request);      

        $entityManager = $this->getDoctrine()->getManager();
        $blog = $entityManager->getRepository(Blog::class)->find($id);
            
        if ($form->isSubmitted()) {
            $file = $request->files->get('blog')['featureImage'];
            if($file != null){
                
                $uploads_directory = $this->getParameter('uploads_directory');
                $filename = $file->getClientOriginalName();
                $file->move(
                    $uploads_directory,
                    $filename
                );
                $blog->setFeatureImage($filename);
            }
            
                
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($blog);
            $entityManager->flush();    

            $this->addFlash('success', 'blog edited successfully!');

            return $this->redirectToRoute('blog');
        }

        return $this->render('blog/edit.html.twig', [ 
            'edit' => $form->createView(),
            'blog' => $blog,
            'id' => $blog->getid(),
        ]);
    } 

}

here is my blog entity file codes......

src/Entity/Blog.php

<?php

namespace App\Entity;

use App\Controller\Admin\BlogController;
use App\Repository\BlogRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Table(name="blogs")
 * @UniqueEntity("blogTitle")
 * @ORM\Entity(repositoryClass=BlogRepository::class)
 */
class Blog
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @Assert\NotBlank(message = "The blog title of category is required.")
     * @ORM\Column(type="string", length=255)
     */
    private $title;

    /**
     * @Assert\NotBlank(message = "The short description of category is required.")
     * @Assert\Length(min=500)
     * @ORM\Column(type="text")
     */
    private $shortDescription;

    /**
     * @Assert\NotBlank(message = "The description of category is required.")
     * @ORM\Column(type="text")
     */
    private $description;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Assert\NotBlank(message = "The feature image of category is required.")
     */
    private $featureImage;

    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 getShortDescription(): ?string
    {
        return $this->shortDescription;
    }

    public function setShortDescription(string $shortDescription): self
    {
        $this->shortDescription = $shortDescription;

        return $this;
    }


    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getFeatureImage(): ?string
    {
        return $this->featureImage;
    }

    public function setFeatureImage(?string $featureImage): self
    {
        $this->featureImage = $featureImage;

        return $this;
    }
}

and here is my template where i used to create edit botton to edit post...

template: blog/index.html.twig

   

{% for blog in blog %}
    <tr>
     <td>{{ blog.id }}</td>
     <td>{{ blog.title }}</td>
     <a href="{{ path('edit', {'id': blog.id, 'title': blog.title}) }}" class="btn btn-outline-info">{{ 'Edit'|trans }}</a>
    </tr>
   {% else %}

2 Answers

Since you're using ParamConverters, but you made a mistake by adding both $blog and $id in your controller method.

Just do this:

/**
* @Route("/{id}/edit", name="edit", methods={"GET","POST"})
*/
public function edit(Request $request, Blog $blog): Response
{     

}

The same goes for your Twig template. You only have to use the id. You should remove title:

{% for blog in blog %}
<tr>
 <td>{{ blog.id }}</td>
 <td>{{ blog.title }}</td>
 <a href="{{ path('edit', {'id': blog.id }) }}" class="btn btn-outline-info">{{ 'Edit'|trans }}</a>
</tr>
{% else %}

Bonus-suggestion: I removed the @return and @param docblocks. Since you're using return/param types, those add no value.

Following on from my comment. This is what i would do so you don't have to inject your Entity. Let the Form class handle it.

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Annotation;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\File\UploadedFile;

use Symfony\Component\DependencyInjection;

use App\Repository\BlogRepository;
use App\Entity\Blog;
use App\Form\BlogType;


class BlogController extends AbstractController
{
 /**
    * @Route("/{id}/edit", name="edit", methods={"GET","POST"})
    * @param Request $request
    * @return Response
    */
    public function edit(Request $request, $id): Response
    {
        $entityManager = $this->getDoctrine()->getManager();
        $blog = $entityManager->getRepository(Blog::class)->find($id);
      
        $form = $this->createForm(BlogType::class, $blog);
        $form->handleRequest($request);      
            
        if ($form->isSubmitted() && $form->isValid()) {
            $file = $request->files->get('blog')['featureImage'];
            if($file != null){
                
                $uploads_directory = $this->getParameter('uploads_directory');
                $filename = $file->getClientOriginalName();
                $file->move(
                    $uploads_directory,
                    $filename
                );
                $blog->setFeatureImage($filename);
            }
            
                
            $entityManager->persist($blog);
            $entityManager->flush();    

            $this->addFlash('success', 'blog edited successfully!');

            return $this->redirectToRoute('blog');
        }

        return $this->render('blog/edit.html.twig', [ 
            'edit' => $form->createView(),
            'blog' => $blog,
            'id' => $blog->getid(),
        ]);
    } 

}
Related