Kevin
Kevin

Reputation: 5092

Symfony Doctrine Sluggable extension in existing database

I had to add in an existing entity a slug field to slugify the field 'name'. But there is already data in this entity and I can't delete them.

I would like to create a console script which can slugify all my 'name' field.

I don't know how to do it because this is not an insertion but just an update...

class SlugCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('generate:geo:slug')
            ->setDescription('Slug generation for GeoBundle ');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get('doctrine')->getManager();
        $regions = $em->getRepository('FMGeoBundle:Region')->findAll();

        if($regions === null){
            throw new Exception('No Region found');
        }

        foreach($regions as $region){
            // ????? Generate the slug here ??
            $em->persist($region);
        }

        $em->flush();
        $output->writeln('Slugs Generated ;) ...');
    }
}

The 'slug' field in my entity:

/**
 * @var string
 *
 * @ORM\Column(name="slug", type="string", length=255)
 * @Gedmo\Slug(fields={"name"})
 */
protected $slug;

Upvotes: 3

Views: 960

Answers (3)

Alsatian
Alsatian

Reputation: 3135

Just saw that the Gedmo library documentation directly answers this question :

Regenerating slug

In case if you want the slug to regenerate itself based on sluggable fields, set the slug to null.

<?php $entity = $em->find('Entity\Something', $id);
$entity->setSlug(null);

$em->persist($entity); $em->flush();

So, in your case you have just to persist the entity, nothing else. Because $slug is already null.

Upvotes: 0

Kevin
Kevin

Reputation: 5092

I found an easier way. You can apparently just set the slug manually like that. And it will slugify the field needed.

foreach ($regions as $region) {
     $region->setSlug($region->getName());

     $this->em->persist($region);
}

Upvotes: 2

systemasis
systemasis

Reputation: 135

The Sluggable extension works on both create and update actions. Therefore, you could just simulate an update by putting a row's name with its own.

Upvotes: 2

Related Questions