DoctrineBehaviors icon indicating copy to clipboard operation
DoctrineBehaviors copied to clipboard

Sluggable doesnt set in DB with PHP 8.1 and Symfony 6

Open romainpltr opened this issue 2 years ago • 3 comments

Hello,

I need to use Sluggable in a project, but when i add Slug properties and Slug trait and i create a object in DB the slug no generate in the database. 180985231-8a994b5a-56c2-4e26-adb8-4a50200b2f1d

romainpltr avatar Jul 29 '22 07:07 romainpltr

Hi @romainpltr

Does your entity implement the SluggableInterface interface as indicated in the documentation ?

Jérôme.

jerome-fix avatar Jul 29 '22 09:07 jerome-fix

Hello, yes she does, but the slug is not write into the database with Symfony 6 and PHP 8.1. I dont know why, but work in Symfony 5.4.

Thanks for your answer. Have a nice day

romainpltr avatar Aug 09 '22 10:08 romainpltr

Hello there. I've stumbled upon this issue as well. In my opinion problem originates from SluggableMethodsTrait::generateSlug().

https://github.com/KnpLabs/DoctrineBehaviors/blob/master/src/Model/Sluggable/SluggableMethodsTrait.php#L22-L37

    /**
     * Generates and sets the entity's slug. Called prePersist and preUpdate
     */
    public function generateSlug(): void
    {
        if ($this->slug !== null && $this->shouldRegenerateSlugOnUpdate() === false) { // <============= HERE
            return;
        }

        $values = [];
        foreach ($this->getSluggableFields() as $sluggableField) {
            $values[] = $this->resolveFieldValue($sluggableField);
        }

        $this->slug = $this->generateSlugValue($values);
    }

To generate any slug at this time (even first one) it is required that shouldRegenerateSlugOnUpdate() method should return true. This behavior is not expected. Also, since it is returning true by default, problem won't be visible without overriding this method.

I believe there might be one more issue - condition $this->slug !== null will always resolve to false, since slug can't be null by design?

I will submit PR shortly, but at this time to workaround this issue don't override shouldRegenerateSlugOnUpdate() method or override generateSlug() and define it accordingly.

broiniac avatar Nov 28 '22 09:11 broiniac