ZF3: Populate select element in form from database

zend-form

#1

Hi

I have populated selects in my forms in ZF2 using the method in this link: https://stackoverflow.com/a/34829272/211351
As i need to init the form i don’t know how to get it working in ZF3. How do i init a form in ZF3?

The goal is to have a select box with values from the database in my form when showing the form in the view. If there is the better version then the one in the link say i would be glad to hear :slight_smile:

/R


#2

Take a look at this it may shed some light :slight_smile:


#3

Maybe some light, but this did not answered the question. :wink:


#4

Here is the factory for your element:

namespace MyModule\Form\Element;

use Interop\Container\ContainerInterface;
use Zend\Form\Element\Select;
use Zend\ServiceManager\Factory\FactoryInterface;

class RoleSelectFactory implements FactoryInterface
{
    /**
     * @inheritDoc
     */
    public function __invoke(
        ContainerInterface $container,
        $requestedName,
        array $options = null
    ) {
        $select = new Select('role_id');

        $select->setLabel('Role');
        $select->setAttributes(['id' => 'role_id']);

        /** @var \Admin\Service\RoleService $roleService */
        $roleService = $container->get('Admin\Service\RoleService');

        $options = [];
        foreach ($roleService->getAllTheRoles() as $role) {
            $options[$role->getId()] = $role->getName();
        }

        $select->setValueOptions($options);

        return $select;
    }
}

No Service Locator, only a Container. Please look also at the interface.

Migration Guide for zend-servicemanager: https://docs.zendframework.com/zend-servicemanager/migration/#factoryinterface


#5

Sorry for no response here, but what solved my problem was to init the form in the same way as in ZF2 but in the controller factory. But that link did help i used it to verify that all parts was correct.

$form = $container->get(‘Zend\Form\FormElementManager’)->get(RoleForm::class);