How to use the translation service inside Entity?

Say I have UserEntity:

$user = new User(007);
echo $user->getName(); // display Bond
echo $user->getGender(); // display "Male";
echo $user->getDesignation() // display "Monsieur Bond" or "Mister Bond"

With this function:

public function getDesignation() {
  if ($this->getGender() == 'Male') return "Monsieur ".$this->getName();
  else return "Madame ".$this->getName();
}

How can I use the translator service inside this Entity to translate "Monsieur" and "Madame"?

It seems that the translation service should be used only inside the controller, but I think that in this case it is appropriate to use it inside this object.

+5
source share
3 answers

, , "", (.. ). , , .

, aldo , . , - , , ..

$entity->setTranslator($translator);

, , ..

{{ entity.property|trans }}).
+8

. , , . , , , ( , , , , ).

- . , ? , . ( ), - factory " "; factory .

+4

, , . , , , , . getDesignation . , , , , .

<div>{% trans %}{{ entity.designation }}{% endtrans %} {{ entity.name }}</div>

.en.yml

Monsieur: Mr.
Madame: Mrs.
+2
source

All Articles