Exactly, you can't wrap variables with t()
. They will get printed, but they won't be translatable. I had a form that saves a user-defined string and wanted that string to be translatable from Drupal's translation interface.
Messed around quite a while with i18n_string()
and its attribute $name
(a $textgroup
and a $context
glued together with :
).
Finally got it: You can provide your own $textgroup
via hook_i18n_string_info()
and later provide any other custom string as $context
(maybe take your module's name to keep things clean).
If you have more than one string in your module pay attention to have every single one of them glued with another custom string to the prior context (textgroup:context:string_1, textgroup:context:string_2, ...).
Here comes a working example:
/**
* Implements hook_i18n_string_info().
*
* This is the most interesting thing here. You create a new
* textgroup your strings will be identified with. Here it's
* simply: Custom modules.
* When you set the i18n-string later you then only add another
* string as context like 'custommodules:any_other_string'.
* See the markup example in the form below.
*/
function MYMODULE_i18n_string_info() {
$groups['custommodules'] = array(
'title' => t('Custom modules'),
'format' => FALSE,
'list' => TRUE,
);
return $groups;
}
/**
* Example form.
*/
function form_example() {
// Just for testing, the first form element prints the translated
// string, so you simply can test it after translation by switching
// your page's language and see it working. This also demonstrates how
// you will print the string everywhere else.
$form['markup'] = array(
'#markup' => i18n_string('custommodules:MYMODULE:string_1', variable_get('user_defined_string', 'Bempo Kohm'), array('update' => TRUE)),
);
$form['string'] = array(
'#type' => 'textfield',
'#title' => t('A beautiful and pure string'),
'#default_value' => variable_get('user_defined_string', 'Bempo Kohm'),
);
$form['button'] = array(
'#type' => 'submit',
'#value' => t('Action'),
);
return $form;
}
/**
* Example form submit handler.
*/
function form_example_submit($form, &$form_state) {
variable_set('user_defined_string', $form_state['values']['string']);
}