eZ\Publish\Core\Helper\TranslationHelper::getTranslatedField PHP Method

getTranslatedField() public method

By default, this method will return the field in current language if translation is present. If not, main language will be used. If $forcedLanguage is provided, will return the field in this language, if translation is present.
public getTranslatedField ( eZ\Publish\API\Repository\Values\Content\Content $content, string $fieldDefIdentifier, string $forcedLanguage = null ) : eZ\Publish\API\Repository\Values\Content\Field | null
$content eZ\Publish\API\Repository\Values\Content\Content
$fieldDefIdentifier string Field definition identifier.
$forcedLanguage string Locale we want the field translation in (e.g. "fre-FR"). Null by default (takes current locale)
return eZ\Publish\API\Repository\Values\Content\Field | null
    public function getTranslatedField(Content $content, $fieldDefIdentifier, $forcedLanguage = null)
    {
        // Loop over prioritized languages to get the appropriate translated field.
        foreach ($this->getLanguages($forcedLanguage) as $lang) {
            $field = $content->getField($fieldDefIdentifier, $lang);
            if ($field instanceof Field) {
                return $field;
            }
        }
    }

Usage Example

 /**
  * @param mixed $contentId ID of a valid Content
  * @param string $fieldIdentifier Field Definition identifier of the Field the file must be downloaded from
  * @param string $filename
  * @param \Symfony\Component\HttpFoundation\Request $request
  *
  * @return \eZ\Bundle\EzPublishIOBundle\BinaryStreamResponse
  */
 public function downloadBinaryFileAction($contentId, $fieldIdentifier, $filename, Request $request)
 {
     if ($request->query->has('version')) {
         $content = $this->contentService->loadContent($contentId, null, $request->query->get('version'));
     } else {
         $content = $this->contentService->loadContent($contentId);
     }
     $field = $this->translationHelper->getTranslatedField($content, $fieldIdentifier, $request->query->has('inLanguage') ? $request->query->get('inLanguage') : null);
     if (!$field instanceof Field) {
         throw new InvalidArgumentException("'{$fieldIdentifier}' field not present on content #{$content->contentInfo->id} '{$content->contentInfo->name}'");
     }
     $response = new BinaryStreamResponse($this->ioService->loadBinaryFile($field->value->id), $this->ioService);
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);
     return $response;
 }
All Usage Examples Of eZ\Publish\Core\Helper\TranslationHelper::getTranslatedField