You can do this:
Create a class that extends Fieldset.
Implement the class InputFilterProviderInterface if you want some sort of validation for this field.
To access the service manager, it needs to Implement the ServiceLocatorAwareInterface and two methods, setServiceLocator () and getServiceLocator ().
By default, the Zend Framework MVC registers an initializer that will inject the ServiceManager instance into any class implementing Zend\ServiceManager\ServiceLocatorAwareInterface. read this
namespace Users\Form;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Form\Element;
use Zend\Form\Fieldset;
class GroupsFieldset extends Fieldset implements InputFilterProviderInterface,
ServiceLocatorAwareInterface
{
/**
* @var ServiceLocatorInterface
*/
protected $serviceLocator;
public function __construct ()
{
parent::__construct('groups');
$this->setLabel('Group');
$this->setName('groups');
$sl = $this->getServiceLocator();
$sm = $sl->get('Users\Model\GroupsTable');
$groups = $sm->fetchAll();
$select = new Element\Select('groups');
$options = array();
foreach ($groups as $group) {
$options[$group->id] = $group->name;
}
$select->setValueOptions($options);
}
/**
* Set serviceManager instance
*
* @param ServiceLocatorInterface $serviceLocator
* @return void
*/
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
return $this;
}
/**
* Retrieve serviceManager instance
*
* @return ServiceLocatorInterface
*/
public function getServiceLocator()
{
return $this->serviceLocator;
}
/**
*
* @return multitype:multitype:boolean
*/
public function getInputFilterSpecification ()
{
return array(
'name' => array(
'required' => true
)
);
}
}
Than in module.php
public function getServiceConfig()
{
return array(
'factories' => array(
'Users\Model\UsersTable' => function($sm) {
$dbAdapter1 = $sm->get('Zend\Db\Adapter\Adapter');
$table1 = new UsersTable($dbAdapter1);
return $table1;
}, // Adapter and table groups here
'Users\Model\GroupsTable' => function($sm) {
$dbAdapter2 = $sm->get('Zend\Db\Adapter\Adapter');
$table2 = new GroupsTable($dbAdapter2);
return $table2;
},
),
);
}
and finally in your Form
$groups = new GroupsFieldset();
$this->add($groups);