How to access translated property using knp labs t

2019-06-24 14:56发布

I am using doctrine translatable and i have a entity which have an translatable attribute. This look like this.

class Scaleitem
{
    /**
     * Must be defined for translating this entity
     */
    use ORMBehaviors\Translatable\Translatable;

    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
}

And i have a file ScaleitemTranslation:

class ScaleitemTranslation
{
    use ORMBehaviors\Translatable\Translation;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $text;


    /**
     * Set text
     *
     * @param string $text
     * @return ScaleitemTranslation
     */
    public function setText($text)
    {
        $this->text = $text;

        return $this;
    }

    /**
     * Get text
     *
     * @return string 
     */
    public function getText()
    {
        return $this->text;
    }
}

I would like to access the text from a controller:

$item = $em->getRepository('AppMyBundle:Scaleitem')->find(1);
dump($item->getText());

This do not work. Have someone a hint for my issue?

1条回答
虎瘦雄心在
2楼-- · 2019-06-24 15:09

As showed in the translatable docs you can access the translation using:

  • $item->translate('en')->getName(); when you want a specific language
  • or adding the __call method in the Scaleitem entity (not on translated entity):

    /**
     * @param $method
     * @param $args
     *
     * @return mixed
     */
    public function __call($method, $args)
    {
        if (!method_exists(self::getTranslationEntityClass(), $method)) {
            $method = 'get' . ucfirst($method);
        }
    
        return $this->proxyCurrentLocaleTranslation($method, $args);
    }
    

    to then use $item->getName(); and always retrieve any "property" in the current locale.

查看更多
登录 后发表回答