2

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?

Dirk J. Faber
  • 4,360
  • 5
  • 20
  • 58
  • Why do you need the slug before flushing? If you use the slug before flushing, you're not sure it's the same slug after flushing. Otherwise, check `\Gedmo\Sluggable\SluggableListener::makeUniqueSlug` and re-use that logic. – Stephan Vierkant Dec 03 '18 at 10:08
  • @StephanVierkant, the Entity is created together with one or more uploaded files. I want these files to be named based on the slug of the Entity, which is turn is based on the `internationalName`. Now you would say, just base it directly on the `internationalName`, but the problem is for two entities with the same name, the file will overwrite. – Dirk J. Faber Dec 03 '18 at 15:36
  • Why can't you upload the files after flushing? – Stephan Vierkant Dec 03 '18 at 20:31
  • @StephanVierkant, I am using the Vich Uploaderbundle which takes care of the uploading, with that it seems it is not possible. – Dirk J. Faber Dec 03 '18 at 22:08

0 Answers0