How to prevent showing/receiving untranslated content?

喜你入骨 提交于 2020-01-07 03:48:29

问题


This is my Distance Cell

public function display()
{
    $this->loadModel('Distances');
    $distances = $this->Distances->find('all',[
        'order' => 'Distances.id ASC',
    ])->toArray();
    $this->set('distances',$distances);
}}

Problem, if content is not yet translated and stored in db, original untranslated content is displayed on the page.

How to prevent this, and show only translated content in current language?


回答1:


The onlyTranslated option

This is unfortunately not documented yet, but the Translate behavior supports a onlyTranslated option, which will cause only those records to be found for which a translation in the current locale exists.

So it could be as simle as enabling that option, either in the configuration when loading the behavior:

$this->addBehavior('Translate', [
      'onlyTranslated' => true,
      // ...
]);

or on the fly:

$this->Distances->behaviors()->get('Translate')->config('onlyTranslated', true);

However, this will only work when the current locale is not the default locale. ie when you've switched the locale in order to view your content in a different language, in most cases however this is exactly what you want and need!

A custom query

In cases where you want to retrieve only those records for which a translation exists, irrespectively of the current locale, or the locale of the translations, then a custom query with an INNER join on the translation table would be an option.

This should be pretty simle using Query::innerJoinWith(). Here's a basic example which should be rather self-explantory:

$TranslateBehavior = $this->Distances->behaviors()->get('Translate');
$translationTable = $TranslateBehavior->config('translationTable');

$distances = $this->Distances
    ->find()
    ->innerJoinWith($translationTable)
    ->order('Distances.id ASC')
    ->toArray();

See also

  • Cookbook > Database Access & ORM > Retrieving Data & Results Sets > Using innerJoinWith
  • Cookbook > Database Access & ORM > Behaviors > Translate > Using a Separate Translations Table
  • API > \Cake\ORM\Behavior\TranslateBehavior::locale()
  • API > \Cake\ORM\Behavior\TranslateBehavior::$_defaultConfig()


来源:https://stackoverflow.com/questions/35258910/how-to-prevent-showing-receiving-untranslated-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!