Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access translated property using knp labs translatable doctrine behaviors

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?

like image 927
smartcoderx Avatar asked Oct 19 '22 15:10

smartcoderx


1 Answers

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.

like image 66
gp_sflover Avatar answered Oct 29 '22 03:10

gp_sflover