How to return translation to toString method in Entity
I have entity and entity translation, both look like this.
class Question
{
use ORMBehaviors\Translatable\Translatable;
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __toString()
{
return (string) $this->getId();
/** @todo
Return translated title instead of id
**/
}
}
class QuestionTranslation
{
use ORMBehaviors\Translatable\Translation;
/**
* @ORM\Column(type="text")
*/
protected $title;
/**
* @ORM\Column(type="text", nullable=true)
*/
protected $explanation;}
}
I would like to return the translated title of this object in my "__toString" method, but how can I access the translated title from "QuestionTranslation" ?.
+3
source to share
1 answer
I am assuming you are using KNP translatable, so you can do it like this:
public function __toString() {
if( $title = $this->translate()->getTitle() ) {
return $title;
}
// if no translation has been added, return empty string instead.
return '';
}
I highly recommend that you set this piece of code to your own method in your entity instead __toString()
. Subsequently, you do something like this:
print $entity->getTitle(); // which call for the translated title.
You can apply this practice to multiple translated fields instead of relying on __toString
.
+3
source to share