Search code examples
symfonydoctrine-ormslug

How I can generate the slug field the from existing data in database - Doctrine Symfony2


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;

Solution

  • 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!