Zend框架2.3翻译形式

时间:2014-07-02 08:23:18

标签: php zend-framework2 translation

我在翻译表单(标签)时遇到问题。 在互联网上搜索了几个小时后,我找不到一个合适的解释如何完成。

有人能在这里给我一个帮助吗?

我正在使用zF2.3手册中的formCollection($ form)

add.phtml

$form->setAttribute('action', $this->url('album', array('action' => 'add')));
$form->prepare();

echo $this->form()->openTag($form); 
echo $this->formCollection($form);
echo $this->form()->closeTag();

AlbumForm.php

 namespace Album\Form;

 use Zend\Form\Form;
 use Zend\I18n\Translator\Translator;

 class AlbumForm extends Form
 {
     public function __construct($name = null)
     {
         // we want to ignore the name passed
         parent::__construct('album');

         $this->add(array(
             'name' => 'id',
             'type' => 'Hidden',
         ));

         $this->add(array(
             'name' => 'title',
             'type' => 'Text',
             'options' => array(
                 'label' => $this->getTranslator()->translate('Name'), //'Naam',
             ),
         ));

         $this->add(array(
             'name' => 'artist',
             'type' => 'Text',
             'options' => array(
                 'label' => 'Code: ',
             ),
         ));

         $this->add(array(
             'name' => 'submit',
             'type' => 'Submit',
             'attributes' => array(
                 'value' => 'Go',
                 'id' => 'submitbutton',
             ),
         ));
     }
 }

错误:

Fatal error: Call to undefined method Album\Form\AlbumForm::getTranslator() in /Applications/MAMP/htdocs/demo/module/Album/src/Album/Form/AlbumForm.php on line 24

1 个答案:

答案 0 :(得分:1)

默认情况下,表单不了解翻译器。你可以做的是,明确并注入翻译。因此,请为表单定义工厂:

'service_manager' => [
    'factories' => [
        'Album\Form\AlbumForm' => 'Album\Factory\AlbumFormFactory',
    ],
],

现在您可以为此表单创建工厂:

namespace Album\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

use Album\Form\AlbumForm;

class AlbumFormFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $sl)
    {
        $translator = $this->get('MvcTranslator');
        $form       = new AlbumForm($translator);

        return $form;
    }
}

现在,完成表单类:

namespace Album\Form;

use Zend\Form\Form;
use Zend\I18n\Translator\TranslatorInterface;

class AlbumForm extends Form
{
    protected $translator;

    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;

        parent::__construct('album');

        // here your methods
    }

    protected function getTranslator()
    {
        return $this->translator;
    }
}