克隆Doctrine实体,其翻译使用DoctrineExtensions进行翻译

时间:2017-09-20 14:04:04

标签: php symfony doctrine doctrine-extensions stofdoctrineextensions

我有使用Translable from DoctrineExtensions的traslated字段的实体。这是它的外观:

/**
 * @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;
    }

}

当我克隆这样的实体时,新的实体只包含在Symfony app中设置的当前语言环境中的翻译。缺少所有其他语言的翻译。

1 个答案:

答案 0 :(得分:0)

您可以使用Gedmo存储库函数获取所有可翻译字段,并将其翻译为新实体。

在你的控制器克隆功能中(例如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();