ZF翻译表格

时间:2013-09-05 17:22:51

标签: php zend-framework2 zend-form zend-form-element zend-translate

我正在使用ZF2而我正在使用翻译器。 在我的应用程序的配置中,我已将翻译器添加到service_manager工厂,因此它将被ZF2助手使用。

这就是我的翻译配置的样子:

'translator' => array(
    'locale' => 'nl_NL',
    'translation_file_patterns' => array(
        array(
            'type' => 'gettext',
            'base_dir' => __DIR__ . '/../language',
            'pattern' => '%s.mo',
        ),
    ),
),

在我的应用程序的module.php文件中,我在onBootstrap方法中有以下代码:

/**
 * Magic to determine the right locale to be used.
 * 
 * Check cookie
 * Check GET parameter
 * Check HOST (application can be used from several domain names)
 */ 

$translator = $serviceManager->get('translator');

// We have to change the current locale if $locale is not null.
if (!is_null($locale)) {          
    $translator->setLocale($locale);

    // The translate helper of the view has some problems with what we're doing.
    // So we'll manually add the translator with the correct locale to the view helper.
    $serviceManager->get('viewhelpermanager')->get('translate')->setTranslator($translator);
}

正如您所看到的,由于onBootstrap方法中的语言环境修改,我已经遇到了一些问题。

现在有两件事可以帮助我: - 帮我找到一种方法将正确的翻译器重新注入表单助手; - 帮助我找到一种方法来实现ZF2喜欢或应该做的方式(我的搜索没有导致解决方案)。

希望你们能帮助我!

2 个答案:

答案 0 :(得分:1)

它应该以相同的方式用于表单助手。

$serviceManager->get('ViewHelperManager')->get('form')->setTranslator($translator);

修改

并使用MvcTranslator服务代替translator

if (!is_null($locale)) {
    $translator = $serviceManager->get('MvcTranslator');
    $translator->setLocale($locale);
    // ...
}

如果你这样做,你甚至不需要setTranslator()来电。

答案 1 :(得分:0)

使用MvcTranslator代替translator

$translator = $serviceManager->get('MvcTranslator');
$translator->setLocale($locale);
$serviceManager->get('ViewHelperManager')
               ->get('translate')->setTranslator($translator);