Get translatable entity from repository with specific locale

Get translatable entity from repository with specific locale

I wanted to have translatable entities in my project. So I used Gedmo translatable through the doctrine extensions bundle for Symfony. When using any kind of entity repository, a listener automatically pulls the right translation according to the current locale (from request or the default one). This is a really good default as most time you will need exactly that behavior.

But now I had the requirement to get all active entities with a specific locale (not the current one). To do this you have to specifically set the locale for the query.

I adapted it within my repository class:

/**
 * Find all active products
 *
 * @param string $locale Locale
 *
 * @return array
 */
public function findAllActiveWithLocale($locale)
{
    $queryBuilder = $this->createQueryBuilder("p");

    $queryBuilder
        ->where("p.active = :active")
        ->setParameter('active', true)
    ;

    $query = $queryBuilder->getQuery();

    $query->setHint(
        Query::HINT_CUSTOM_OUTPUT_WALKER,
        'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker'
    );

    $query->setHint(TranslatableListener::HINT_TRANSLATABLE_LOCALE, $locale);

    return $query->getResult();
}