Skip to content

Instantly share code, notes, and snippets.

@pitpit
Last active March 21, 2023 11:32
Show Gist options
  • Save pitpit/ce6df260fea08e61a6e5c5e7cb668d59 to your computer and use it in GitHub Desktop.
Save pitpit/ce6df260fea08e61a6e5c5e7cb668d59 to your computer and use it in GitHub Desktop.
gedmo/doctrine-extensions translatable behavior (or stof/doctrine-extensions-bundle) and alice fixtures

Translated alice fixtures for gedmo translatable entities

Here's a way that doesn't require any additional code to create translated fixtures via alice.

The example works with the single translation table from Gedmo (ext_translations) but I assume it also works in a multi tables model.

My entity:

#src/Entity/Article.php
namespace App\Entity;

/**
 * @ORM\Table(name="articles")
 */
class Article
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=false)
     * @Gedmo\Translatable
     */
    private $title;
    
    //...
}

A fixture for my entity (in the main language):

#fixtures/articles.yml
App\Entity\Article:
  article_1:
    title: 'title in english'

and its translation directly using Gedmo entity:

#fixtures/translations.yml
Gedmo\Translatable\Entity\Translation:
  article_1_translation_fr:
    locale: fr
    objectClass: 'App\Entity\Article'
    field: 'title'
    foreignKey: '@article_1'
    content: 'title in french'

If you run fixtures now (bin/console hautelook:fixtures:load with symfony), you'll get the error:

Object of class App\Entity\Article could not be converted to string

So you need to alter the Entity and add the following method in class:

#src/Entity/Article.php

//...

class Article
{
    //...

    public function __toString(): string
    {
        return strval($this->id);
    }
}

And voila!

I tried to change foreignKey: '@article_1' to foreignKey: '@article_1->id' or foreignKey: '@article_1->getId()' but it does not work :(

Tested with a combination of:

  • hautelook/alice-bundle:2.8.0
  • nelmio/alice:3.7.4
  • theofidry/alice-data-fixtures:1.3.1
  • gedmo/doctrine-extensions:3.0.3
  • stof/doctrine-extensions-bundle:1.5.0
@svenjehles
Copy link

Does this still work? I'm trying it with a combination of

  • hautelook/alice-bundle: 2.11.0
  • nelmio/alice: 3.12.2
  • theofidry/alice-data-fixtures: 1.6.0
  • gedmo/doctrine-extensions: 3.10.0
  • stof/doctrine-extensions-bundle: 1.7.1

My issue is that while the entry in ext-translations table is being made, that the foreign_key column stays empty (empty string, not NULL).

This makes sense because my entity does not have an id before persisting, thus the __toString just returns an empty string...
So I end up with translations that do not relate to a field.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment