Skip to content

Instantly share code, notes, and snippets.

@arfaram
Last active January 11, 2021 12:24
Show Gist options
  • Save arfaram/eae7c3914122957dc63697ee2f7d0253 to your computer and use it in GitHub Desktop.
Save arfaram/eae7c3914122957dc63697ee2f7d0253 to your computer and use it in GitHub Desktop.
Get a current translated field data using different way in eZ Platform.

Assume we want to get the translated value of a Text Line (ezstring) field with identifier title.

Using content object

        $contentService = $this->get('ezpublish.api.service.content');
        $content = $contentService->loadContent('<CONTENT-ID>');
        $language = $content->versionInfo->initialLanguageCode;  
        $title = $content->fields['title'][$language]->text;
        //Or
        $title = $content->getFieldValue('title',$language)->text;   
        //similar to
        $title = $content->getField('title',$language)->value->text;

Using a translation helper

        $contentService = $this->get('ezpublish.api.service.content');
        $content = $contentService->loadContent(<CONTENT-ID>);
        $language = $content->versionInfo->initialLanguageCode;  
        $translationHelper = $this->get('ezpublish.translation_helper');
        $title = $translationHelper->getTranslatedField($content, 'title', $language)->value->text;

Using the getFieldsByLanguage()

        $contentService = $this->get('ezpublish.api.service.content');
        $content = $contentService->loadContent(<CONTENT-ID>);
        $language = $content->versionInfo->initialLanguageCode;
        $title = $content->getFieldsByLanguage($language)['title']->value->text;

Using loadVersionInfo()

  • loadVersionInfo() contains only meta information about the current version. The content Fields data are not provided like above example.
  • This will just return the content name as defined in the content name schema.
        $contentService = $this->get('ezpublish.api.service.content');
        $contentInfo = $contentService->loadContentInfo(<CONTENT-ID>);
        $contentInfoVersionInfo = $contentService->loadVersionInfo($contentInfo, $contentInfo->currentVersionNo);
        $language = $contentInfoVersionInfo->initialLanguageCode;
        $contentName = $contentInfoVersionInfo->getName($language);

This is similar to:

        $contentService = $this->get('ezpublish.api.service.content');
        $content = $contentService->loadContent(<CONTENT-ID>);
        $language = $content->versionInfo->initialLanguageCode;
        $contentName = $content->getName($language);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment