Translating views strings programmatically in Drupal 8

Posted on Wednesday, September 20, 2017
Translating views strings programmatically in Drupal 8

In Drupal 8 strings can be translated with .po files or translation interface provided by the locale module. But views strings like sort options, header, footer or any other string can only be translated through configuration translation and can be enabled by enabling "Configuration Translation" module.

Now each view will have a "Translate View" tab on edit view page, through which translations can be added for each language.

Drupal 8 views translate tab

Translate Views tab provide an interface for that particular views specific strings.

Drupal 8 views translate tab interface

But if for some reason you need to added translation for a view programmatically and not with interface then you can use this Config Override to set the translations.

 

<?php
$recent_view 
= \Drupal::languageManager()
    ->
getLanguageConfigOverride('ar''views.view.content_recent');
  
$recent_view->set('display.default.display_options.exposed_form.options.exposed_sorts_label''رتب حسب');
  
$recent_view->set('display.default.display_options.exposed_form.options.bef.sort.advanced.combine_rewrite''الاسم تصاعدي|الاسم من أ إلى ي
الاسم تنازلي|الاسم من ي إلى أ
السعر تنازلي|السعر من الأعلى إلى الأدنى
السعر تصاعدي|السعر من الأدنى إلى الأعلى'
);
  
$recent_view->set('display.default.display_options.exposed_form.options.sort_asc_label''تصاعدي');
  
$recent_view->set('display.default.display_options.exposed_form.options.sort_desc_label''تنازلي');
  
$recent_view->set('display.default.display_options.sorts.title.expose.label''الاسم');
  
$recent_view->set('display.default.display_options.header.result.content''@total القطع');
  
$recent_view->save();
?>
Disqus Comments