Creating multilingual variables
A super quick blast from the past today; a Drupal 7 based article!
I had some work recently to create a new "setting" variable for one our Drupal 7 multilingual sites, which meant creating multilingual versions of those variables. I soon found out that there is very much a correct way - or order - to achieve this as I got this one very wrong (I had to re-instate my DB!). So here I am writing a very quick guide to help those from my wrong doings.
(This guide assumes you have a multilingual site setup with i18n's Variable translation module.)
Four simple steps to achieve a multilingual variable:
- Declare your new variables via
hook_variable_info
function your_module_name_variable_info($options = array()) { $variables['your_variable_name'] = array( 'title' => t('Foo'), 'description' => t('A multi-lingual variable'), 'type' => 'string', 'default' => t('Bar'), 'localize' => TRUE, );}
The options you can set in this hook are well documented - start reading from the Variable module's project page.
- Flush the variable cache and get your new variables registered using an update hook. The meat of the update hook is below -- note that this assumes you want all all of the possibly-localizable variables to be made translatable:
variable_cache_clear(); /** @var VariableRealmControllerInterface $controller */ if ($controller = variable_realm_controller('language')) { $variables = $controller->getAvailableVariables(); $controller->setRealmVariable('list', $variables); } else { throw new DrupalUpdateException('Could not set up translatable variables. Try <a href="https://www.computerminds.co.uk/admin/config/regional/i18n/variable">manually setting them</a>.'); }
- Create or alter your settings form (I'm assuming it uses
system_settings_form()
or is already recognised by the i18n/variable systems as a form containing translatable variables) and add your new form elements. Make sure the element(s) are the same as your newly created variable(s) - I use a $key variable to avoid any mistakes there!
$key = 'your_variable_name';$form[$key] = array( '#type' => 'textfield', '#title' => t('Foo'), '#default_value' => variable_get($key, 'Bar'),);
Head over to /admin/config/regional/i18n/variable or your settings form to see your new multilingual variable in all it's glory!