D
D
Dmitry2021-03-17 22:02:10
symfony
Dmitry, 2021-03-17 22:02:10

How to get an entry by slug correctly?

Good evening.

Help, please, to solve the problem.

There is an entity Region, there is also an embeddable class Name.

/*
 * @ORM\Entity
 * @ORM\Table(name="location_regions")
 */
class Region
{
    /**
     * @var Id
     * @ORM\Column(type="location_region_id")
     * @ORM\Id
     */
    private Id $id;
    /**
     * @var Name
     * @ORM\Embedded(class="Name", columnPrefix=false)
     */
    private Name $name;

    /....../
   public functon getName(): Name
  {
       return $this->name;
  }

#############################################
/**
 * @ORM\Embeddable()
 */
class Name
{
    /**
     * @var string
     * @ORM\Column(type="string", unique=true)
     */
    private string $name;
    /**
     * @var string
     * @ORM\Column(type="string", unique=true, nullable=true)
     * @Gedmo\Slug(fields={"name"})
     */
    private string $slug;

    public function __construct(string $name)
    {
        Assert::notEmpty($name);
        $this->name = $name;
    }

    public function getValue(): string
    {
        return $this->name;
    }

    public function getSlug(): string
    {
        return $this->slug;
    }
}


When creating a new region, the slug is automatically written to the database.

When I try to switch to viewing a particular region, I get an error.
Unable to guess how to get a Doctrine instance from the request information for parameter "region".


I understand that doctrine cannot understand which record to get from the database.

Action in controller

/**
     * @param Region $region
     * @param RegionFetcher $fetcher
     * @return Response
     *
     * @Route("/region/{slug}", name=".show")
     * @ParamConverter("region", options={"mapping": {"slug": "slug"}})
     */
    public function show(Region $region, RegionFetcher $fetcher): Response
    {
        $region = $fetcher->find($region->getId()->getValue());
        return $this->render('app/admin/location/regions/show.html.twig', ['region' => $region]);
    }


Link to go from home page

<a href="{{ path('location.regions.show', {'slug': region.slug}) }}">{{ region.name }}</a>


How correctly in this case to explain doctrine through the annotation which record to get from the database?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2021-03-17
@slo_nik

public function show(string $slug, RegionFetcher $fetcher): Response
    {
        $region = $fetcher->findOneBy(["name.slug" => $slug]);
        return $this->render('app/admin/location/regions/show.html.twig', ['region' => $region]);
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question