Question

I've been working the past 2 hours on translating my slug without much success. First, let's take a look at my entity :

/**
 * BlogPost
 *
 * @ORM\Entity
 */
class BlogPost implements Translatable
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @Gedmo\Translatable
     * @ORM\Column(name="title", type="string", length=128)
     */
    private $title;

    /**
     * @Gedmo\Slug(fields={"title"})
     * @Gedmo\Translatable
     * @ORM\Column(length=128)
     */
    private $slug;

It's pretty straightforward. Now, when I do :

$em = $this->getDoctrine()->getManager();

$blogPost = new BlogPost();
$blogPost->setTitle('my title in FRANCAIS');
$blogPost->setTranslatableLocale('fr_ca');
$em->persist($blogPost);
$em->flush();

$blogPost->setTitle('my title in ENGLISH');
$blogPost->setTranslatableLocale('en_us');
$em->persist($blogPost);
$em->flush();

Only my title gets translated, but my slug is only in french. I tried that solution from the doc ... but there is no TranslationListener (the file does not exist). There is only one note in the doc that doesn't mean much to me :

Note: these translations will not be processed as ordinary fields of your object, in case if you translate a slug additional translation will not know how to generate the slug, so the value as an additional translation should be processed when creating it.

I must admit that I feel in a dead end. Could someone please share some knowledge on that matter!

Was it helpful?

Solution

I suggest you to use the KnpDoctrineBehavious Bundle. It makes is very simple to translate any property of your entity:

class BlogPost
{
    use ORMBehaviors\Translatable\Translation;

    // anything that should not be translated
    // follows in this class
}

And add a translation entity:

class BlogPostTranslation
{
    /**
     * @Gedmo\Slug(fields={"title"})
     * @ORM\Column(length=128)
     */
    private $slug;

    // ...
}

Now you can acces any translation like this:

$blogPost->getSlug(); // default language slug
$blogPost->translate('en')->getSlug(); // English slug
$blogPost->translate('fr')->getSlug(); // French slug

Don't forget to call $entity->mergeNewTranslations(); after $em->persist($entity); to update the translation table.

Edit:

Note that the DoctrineBehaviours Bundle also supports a way better Sluggable. Use it like it's shown in their documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top