Use the ServerUrl helper as in the example below:
Defining Form:
use Zend\Form\Form;
use Zend\ServiceManager\ServiceLocatorAwareTrait;
use Zend\Form\Element\Text;
use Zend\Form\Element\Image;
class Perfil extends Form
{
use ServiceLocatorAwareTrait;
public function init() {
// Obtendo o helper ServerUrl
$serverUrl = $this->getServiceLocator()
->get('ViewHelperManager')
->get('ServerUrl');
// Criando elementos do formulário
$name = new Text();
$name->setLabel('Nome')
->setName('name');
$avatar = new Image();
$avatar->setLabel('Imagem')
->setName('avatar')
->setAttribute('src', $serverUrl->__invoke('/images/100x100.gif'));
$this->add($name)
->add($avatar);
}
}
Using the form on a controller by instantiating the form:
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Form\Perfil;
class IndexController extends AbstractActionController
{
public function indexAction()
{
$form = new Perfil();
$form->setServiceLocator($this->getServiceLocator());
$form->init();
return new ViewModel(array(
'form' => $form
));
}
}
Can also be used by making dependency injection through the Module class
<?php
namespace Application;
use Zend\ModuleManager\Feature\ServiceProviderInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Application\Form\Perfil;
class Module implements ServiceProviderInterface
{
public function getServiceConfig()
{
return array(
'factories' => array(
'Application\Form\Perfil' => function (ServiceLocatorInterface $serviceLocator) {
$form = new Perfil();
$form->setServiceLocator($serviceLocator);
$form->init();
return $form;
}
)
);
}
}
Calling the service created in Module.php on your controller:
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Form\Perfil;
class IndexController extends AbstractActionController
{
public function indexAction()
{
$form = $this->getServiceLocator()->get('Application\Form\Perfil');
return new ViewModel(array(
'form' => $form
));
}
}
I hope I have helped!