4

I have a problem with the DoctrineBehaviors bundle. I'm trying to get the translation for a specific language (French) for an entity that doesn't have the French translation. It returns the fallback language, that is OK for the frontend, but I need to know if that language have a translation, because I need to fill in my backend.

How can I know if a entity's field is translated to an specific language?

timothymctim
  • 205
  • 1
  • 9
David
  • 321
  • 2
  • 11

1 Answers1

0

Using the Translatable entity, you can get all translations known to your specific entity (documentation).

$product = $this->getDoctrine()
    ->getRepository('AppBundle:Product')
    ->find($productId);

$repository = $this->getDoctrine()->getRepository('Gedmo\Translatable\Entity\Translation');
$translations = $repository->findTranslations($product);

The variable $translations now contains a keyed array, e.g.,

array(2) {
  ["en_US"]=>
  array(1) {
    ["name"]=>
    string(8) "Keyboard"
  }
  ["fr_FR"]=>
  array(1) {
    ["name"]=>
    string(7) "Clavier"
  }
}

Finding out if the entity is translated can is now simply checking whether the locale is in the array keys.

if (!array_key_exists('fr_FR', $translations)) {
    throw $this->createNotFoundException('product description not available in French');
}

Note that the Translatable entity does not contain the default locale (unless you have set setPersistDefaultLocaleTranslation to true).

timothymctim
  • 205
  • 1
  • 9