Changing the formula to calculate plural forms for a language for Drupal 8

Posted on Friday, September 22, 2017
Changing the formula to calculate plural forms for a language for Drupal 8

 

Multilingual functionality is in the core by Drupal 8 release. One of the functionality provided by multilingual modules in Drupal 8 is to allow a user to add different plural forms to the string as per the language.

Generally, different languages could have their own formula to calculate the forms of plurals. Normally in Drupal's translation interface, this is how the plural form looks like as the English language got 1 to 1 kind of mapping for plural forms. For example "1 minute" is a singular form and "2 minutes" is plural and similarly for any other number greater than 1 only one type of plural form will be used.

Plural in english

But on the other hand, if you look at the plural form for the Arabic language it might show more options to input different values for different kind of plural forms. This might be confusing but each language could have a different formula to calculate this as mentioned earlier.

Arabic plural form drupal

The formula used to calculate the plural form in Drupal is set at the time of language enable are hardcoded and are not configurable if someone wants to change the number of plural forms should be available for a particular language in the translation interface. For example, by default in Drupal, the multilingual system provides 6 input fields for adding plural forms for a single text and if we want to change it to 4 input fields.

1st for singular form

2nd for 0 and 2 items

3rd for 3-10 items

4th for rest of the numbers

To alter the default plural formula and make it sensible in respect to the language you just need to run this snippet of code to change the formula as per your need.

<?php
  
// Reset the formula to calculate plural in Arabic language.
  
$formulae = \Drupal::state()->get('locale.translation.formulae', []);
  if (isset(
$formulae['ar'])) {
    
$formulae['ar'] = [];
    
$formulae['ar']['plurals'] = 5;
    
$formulae['ar']['formula'][0] = 1;
    
$formulae['ar']['formula'][1] = 0;
    
$formulae['ar']['formula'][2] = 2;
    
$formulae['ar']['formula'][3] = 3;
    
$formulae['ar']['formula'][4] = 3;
    
$formulae['ar']['formula'][5] = 3;
    
$formulae['ar']['formula'][6] = 3;
    
$formulae['ar']['formula'][7] = 3;
    
$formulae['ar']['formula'][8] = 3;
    
$formulae['ar']['formula'][9] = 3;
    
$formulae['ar']['formula'][10] = 3;
    
$formulae['ar']['formula']['default'] = 4;
    \
Drupal::state()->set('locale.translation.formulae'$formulae);
  }
?>

 

Once this code snippet is run through hook_install() or hook_upate() hooks, translation interface will show configured number of inputs field for plural form

Disqus Comments