5

This is my entity, and i used a gedmo annotation, when a new register is created (persits) the slug works correctly but how can i auto-generate slug texts from existing database

 /**
 * @Gedmo\Slug(fields={"name"})
 * @ORM\Column(type="string", unique=true)
 */
protected $slug;
Edgar Alfonso
  • 675
  • 2
  • 6
  • 20
  • what do you want to do exactly with this slug 'persisted' ? – miltone Jan 28 '16 at 21:01
  • 1
    You need to update the 'name' field - simply persisting the entity doesn't work. I think gedmo listens for changes specifically to the named field. Otherwise you'd have to write a small function to do it for you. – MistaJase Jan 28 '16 at 21:41
  • Have a look at this https://knpuniversity.com/screencast/symfony2-ep3/doctrine-extensions#configuring-slug-to-be-set-automatically – Shairyar Jan 29 '16 at 06:48
  • More info on manual generation of the slugs here: http://stackoverflow.com/questions/18556682/generating-doctrine-slugs-manually – Dimitry K Mar 30 '17 at 17:46

2 Answers2

5

You have to do it manually by selecting all the value without a slug and setting the slug value to null as describe inside the documentation of the Sluggable Behavior.

https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/sluggable.md#regenerating-slug

Benoît
  • 594
  • 4
  • 11
5

Here is a naive Symfony command to regenerate all slugs of the given classes:

<?php

namespace App\Command;

use App\Entity\Foo;
use App\Entity\Bar;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class RegenerateSlugs extends Command
{
    private $doctrine;

    protected static $defaultName = "app:regenerate-slugs";

    public function __construct(ManagerRegistry $doctrine)
    {
        parent::__construct();

        $this->doctrine = $doctrine;
    }

    protected function configure(): void
    {
        $this
            ->setDescription('Regenerate the slugs for all Foo and Bar entities.')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): void
    {
        $manager = $this->doctrine->getManager();

        // Change the next line by your classes
        foreach ([Foo::class, Bar::class] as $class) {
            foreach ($manager->getRepository($class)->findAll() as $entity) {
                $entity->setSlug(null);
                //$entity->slug = null; // If you use public properties
            }

            $manager->flush();
            $manager->clear();

            $output->writeln("Slugs of \"$class\" updated.");
        }
    }
}

Hi hope it may help someone stumbling upon this question!

BroodjeBE
  • 95
  • 10
Kévin Dunglas
  • 2,864
  • 2
  • 23
  • 39