I have an entity Book
. Title of this Book
is stored in different languages (the entity Book
is associated with BookTranslates
as OneToMane
).
The entity Book
is used as a form field in several places (like select). For this, I need to set __toString ()
for the Book
entity, which will return the title of the Book
in the user's language.
I tried to get the user inside the entity by passing TokenStorageInterface
in the __construct ()
method of the Book
class, but the doctrine never calls the __construct ()
method in that case.
Brief statement of the problem:
__toString ()
in entity must return a field of one of the related entities. Which specifically related entities - depends on the current user. How to implement it correctly?
This is one of the possible solutions:
Please leave entity __construct
alone.
I assume you have entity with translations
. You entity can (should) have method like setCurrentLocale
to be aware of current locale. Method can be called manually or in e.g. Doctrine2 postLoad
event:
public function setCurrentLocale(string $locale)
{
$this->locale - $locale;
}
Now in __toString
while translating e.g. title
your entity can fetch proper translation.