Reputation: 23
I have a problem with translating form (labels). After searching hours on the internet, I can't find a decent explanation how it should be done.
Anybody who can give me a help here?
I'm using the formCollection($form) as written in the ZF2.3 manual
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',
),
));
}
}
Error:
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
Upvotes: 0
Views: 472
Reputation: 13558
The form has no knowledge of a translator by default. What you can do, is make it explicit and inject a translator. Therefore, define a factory for your form:
'service_manager' => [
'factories' => [
'Album\Form\AlbumForm' => 'Album\Factory\AlbumFormFactory',
],
],
Now you can create a factory for this form:
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;
}
}
Now, finalize your form class:
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;
}
}
Upvotes: 2