Symfony2 and Translatable example

To set up translatable have a look at my previous post: Symfony2 and DoctrineExtensions.

First lets have a look at the translatable settings from the previous post

// app/config/config.yml
...
# Doctrine Extensions Configuration
stof_doctrine_extensions:
        default_locale: en_us
        translation_fallback: true
        orm:
            default:
              timestampable: true
              translatable: true

The settings above tells that we want to use en_us as our language and that we want fo fallback to that languge if current lange does not exists.

So to use Translatable you need to add this above your entity class:

use Gedmo\Translatable\Translatable;

Then you need to add this to your entity class:

/**
 * @Gedmo\Locale
 * Used locale to override Translation listener`s locale
 * this is not a mapped field of entity metadata, just a simple property
 */
private $locale;

public function setTranslatableLocale($locale)
{
    $this->locale = $locale;
}

Thats all you need to get started. To make a value Translatable you decorate it like this:

/**
 * @var string $name
 *
 * @ORM\Column(name="name", type="string", length=255, unique="true")
 * @Gedmo\Translatable
 */
private $name;

Ok thats all needed to use Translatable this will map all translations to a table named ext_translations. That is a bad idea if you have a lot of data to translate (or if you like me like to have some order on things). A better way is to create an entity that stores the translations.

Create an entity to store the translations with:


As you can see I created a AccommodationType translator. To use this we need to decorate AccommodationType like this:

/**
 * MLK\AccommodationBundle\Entity\AccommodationType
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass=
"MLK\AccommodationBundle\Entity\AccommodationTypeRepository")
 * @Gedmo\TranslationEntity(class=
"MLK\AccommodationBundle\Entity\AccommodationTypeTranslation")
 */
class AccommodationType implements Translatable

So now the translations for my AccommodationType will end up in the database table AccommodationTypeTranslation. Much Nicer!

Happy hacking

21 Responses to “Symfony2 and Translatable example”

  1. Roger

    Thanks a lot for the article, it helped a lot!
    Just two questions for the last part:

    * In the AccommodationTypeTranslation class, you put the index name as “translations_lookup_idx”, which gives me an error, since it already exists in a table called ext_translations. The same for “lookup_unique_idx”. Just changing the name, it works.

    *This is the important one: It’s ok that the ext_translations and ext_translations are still created, even though I don’t put the private $locale; variable in the AccommodationType class?
    I don’t know if I’m doing it well, and if so, why is the table still created.

    Thank you!

  2. Mikael Ohlsson

    Hi nice that you liked the article :)

    The “translations_lookup_idx” is just a name for the constraint, it is not important.. If you drop the table and then recreate it, the name should probably work.

    The table is created automaticly beacuse you have automatic mapping on in your config file. If you do not want the tables created check the information at https://github.com/stof/StofDoctrineExtensionsBundle/blob/master/Resources/doc/index.rst under “Add DoctrineExtensionsBundle to your mapping”

    Happy hacking!

  3. Roger

    Thank you Mikael, I’ll will try it.

    By the way, is the DoctrineExtensionsBundle the official way to do the things or just a way to do them until the official product is finished? I think that this point is interesting to put it here for the newbies like me!

  4. niko

    Very nice article, helped me to set up translatable plugin, but I fail to load the translated content based on the current locale of the user. Any tips what I am missing?

  5. etoileweb

    Hello, I’m new to Symfony and I’m using version 2.0.12. In my AmcNewsBundle Entity’s folder, I just have News.php and NewsRepository.php files. I got a little bit puzzled when you talked about a AccommodationTypeTranslation entity to create. Due to file naming conventions, must this entity’s name be based on a previous xxxxType entity ? As far as I know, only classes for building forms have their names ending in xxxxType. I don’t understand. Could you give me some clarifications please ?

  6. Mikael Ohlsson

    Just the name that I have in the database… Could just as well be called TypeOfAccommodation…. Not anything important…

  7. etoileweb

    Ok, thank you, and thank you for your quick reply. Do I need to run a specific task after that ? A app/console doctrine:schema:update –force or something else ?

  8. sam

    at what point is the new database table ‘ext_translations’ generated ?

    I followed all the steps but receive

    ‘Class Gedmo\Translatable\Entity\Translation is not a valid entity or mapped super class. ‘

    and there is no new table in my db either ..?

  9. Mikael Ohlsson

    It gets generated when you do
    php app/console doctrine:schema:update –force

    You should note the date when this article was posted, the docs might have changed. If so please tell me how and I will update the article.

  10. sam

    Tables are beeing generated now, but i still have 2 issues

    i have to do this in order to populate the data ..?:

    $article->setName(’4my standard title en’);
    $em->persist($article);
    $em->flush();
    $article->setTranslatableLocale(‘de’);
    $article->setName(’4my standard title de’);
    $em->persist($article);
    $em->flush();
    $article->setTranslatableLocale(‘fr’);
    $article->setName(’4my standard title fr’);
    $em->persist($article);
    $em->flush();
    all is saved correctly (i assume)

    but when doing

    $session->setLocale(‘fr’);
    and then retreive a list of entities using
    $cats = $em->getRepository(‘NonoAdminBundle:Productcat’)->findByProject($id);

    the cats are all displayed using their EN (default) name..

    Any ideas, as i’ve been going crazy for a few hours now ..

  11. sam

    nvm, i seem to have gotten it working now, by using the before-mentioned solution ..

    Thanks a bunch for all your quick help!!

    Ill be bookmarking yours site for further reference.

    Maybe i’ll even send u a few articles form time to time, when i come across something interresting i have to do in symfony2.

    Thx

    Sam

  12. sam

    hi again,

    Today i upgraded my project from 2.0 to 2.1, among ALOT of other things, the translatable is not working anymore

    It is still saving them in the table correctly, but not displaying them ..

    (Same as it was before implementing last fix )

  13. amit

    I am using gedmo bundle, its working fine. But problem is i want to create form like Category where there are two entity. Title and Description. These two fields should be show as per i have added languge in laguage table. So it should be in arrray. I have tried to show form structure under here:
    lable = English title

    lable = French Title

    I have managed all language in Tab selection in form view
    So, please advice.
    Thanks,
    Amit Patel.

  14. amit

    I am using gedmo bundle, its working fine. But problem is i want to create form like Category where there are two entity. Title and Description. These two fields should be show as per i have added languge in laguage table. So it should be in arrray. I have tried to show form structure under here:
    lable = English title

    lable = French Title

    I have managed all language in Tab selection in form view
    So, please advice.
    Thanks,
    Amit Patel.

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>