Doctrine extension: generate slug before flushing to database

422 Views Asked by At

Using the StofDoctrineExtensionsBundle (for Symfony) I generate a slug for my entity Institution based on its attribute internationalName like this:

Institution.php

/**
 * @ORM\Column(type="string", length=100, unique=true)
 * @Gedmo\Slug(fields={"internationalName"})
 */
private $slug;

In my config settings i have set sluggable: true and generating the unique slug works as expected when creating a new Institution or updating an existing one.

I need the generated slug in the controller before flushing to the database. The problem is, the slug is generated when the new entity is flushed to the database. I have searched for this issue and discover two questions with no satisfying answers, here and here.

The best suggestion changing the getSlug() in the Entity like this:

public function getSlug()
{
    if (!$this->slug) {
        return Urlizer::urlize($this->getInternationalName());
    }
    return $this->slug;
}

However, the internationalName for my entity does not have to be unique, so the 'pre-flushed slug' can be an existing one if the internationalName already exists in the database, which creates a problem in my controller.

Is there a solution to generating a unique slug pre-flush?

0

There are 0 best solutions below