Cloning Doctrine entity with translations made with DoctrineExtensions Translatable

682 Views Asked by At

I have entities with traslated fields using Translatable from DoctrineExtensions. This is how it looks:

/**
 * @ORM\Table
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\SurveyAnswerRepository")
 * @Gedmo\Loggable
 */
class SurveyAnswer
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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

    /**
     * @Gedmo\Locale
     * Used locale to override Translation listener`s locale
     * this is not a mapped field of entity metadata, just a simple property
     * and it is not necessary because globally locale can be set in listener
     */
    private $locale;

    public function __clone()
    {
        if ($this->getId())
        {
            $this->id = null;
        }
    }

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

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    public function getName()
    {
        return $this->name;
    }

}

When I clone such entity, the new one consist only translation in current locale set in Symfony app. Translations for all other languages are missing.

1

There are 1 best solutions below

0
On

You can use the Gedmo repository functions to get all translatable fields, and translate them for the new entity.

In your controller clone function (e.g. SurveyController::duplicateAction):

$newEntity = clone $entity;
$em = $this->getDoctrine()->getManager();
$transRepo = $em->getRepository('Gedmo\Translatable\Entity\Translation');

// Get all translations from original entity
$translations = $transRepo->findTranslations($entity);
foreach ($translations as $locale => $fields) {
    foreach ($fields as $field => $value) {
        // Add new translation for new entity, per locale, per field
        $transRepo->translate($newEntity, $field, $locale, $value);
    }
}
$em->flush();