我創建了一個名爲AbstractApplicationForm
的抽象表單類。我想服務定位器注入到它通過Zend\ServiceManager\ServiceLocatorAwareInterface
能夠訪問譯者:注入ServiceLocator並將其用於抽象的Zend Form基類
namespace Application\Form;
use Zend\Form\Form;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
abstract class AbstractApplicationForm
extends Form
implements ServiceLocatorAwareInterface
{
protected $serviceLocator;
protected $translator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
public function getTranslator()
{
if (!$this->translator) {
$this->translator = $this->getServiceLocator()->get('translator');
}
return $this->translator;
}
}
我的申請表繼承這個類像以下:
namespace Trade\Form;
use Zend\Captcha;
use Zend\Captcha\Image;
use Zend\Form\Element;
use Application\Form\AbstractApplicationForm;
class MemberForm extends AbstractApplicationForm
{
public function init()
{
$this->setAttribute('method', 'post');
// Add the elements to the form
$id = new Element\Hidden('id');
$first_name = new Element\Text('first_name');
$first_name->setLabel($this->getTranslator('First Name'))
這樣,我可以使用getTranslator翻譯標籤。
到目前爲止這麼好。在我的控制器動作,我創建的形式是這樣的:
public function joinAction()
{
// Create and initialize the member form for join
$formManager = $this->serviceLocator->get('FormElementManager');
$form = $formManager->get('Trade\Form\MemberForm');
結果是一個例外的ServiceManager:
的Zend \的ServiceManager \的ServiceManager ::得到無法獲取或創建翻譯實例
我沒有任何其他定義在Module.php
或module.config.php
,我不認爲我需要。我在module.config.php
定義的翻譯是這樣的:
'translator' => array(
'locale' => 'en_US',
'translation_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
,當我在控制器中得到它的正常工作:
$sm = $this->getServiceLocator();
$this->translator = $sm->get('translator');
所以譯者配置實際上是正確的,但我無法找回它以我的形式。 有人知道我在做什麼錯嗎?
謝謝你的解釋。現在完美。 – PWansch 2013-03-13 02:28:18
這似乎不適用於字段集,如何在那裏使用翻譯器? – Aise 2016-01-31 18:14:28