php - How to load select option from database in zf2 -


i have been following zf2 guide blog have created controller, factory, form, mapper, model, service, view etc

in form have select element

$this->add(array(        'type' => 'select',          'name' => 'roleid',   'attributes' =>  array(     'id' => 'roleid',     'options' => array(         '1' => 'admin',         '2' => 'manager',     ),   ),   'options' => array(     'label' => 'role',   ), )); 

now in form want load option role database.
tried loading option creating simple function, can accessed in element below, not able fetch result. have created controller, factory, form, mapper, model, service , view, can crud operation on role.

$this->add(array(        'type' => 'select',          'name' => 'roleid',   'attributes' =>  array(     'id' => 'roleid',     'options' => $this->getallroles(),   ),   'options' => array(     'label' => 'role',   ), ));  public function getallroles() {   $roles = $this->getservicelocator()->get('admin\service\roleservice');   $allroles = $this->getalltheroles();     return $allroles; } 

can guide me how can load roles in option listed in indexaction following blog post id , name of role.

you create reusable form element pre-populated roles. must register service form element manager in module.config.php.

return [     'form_elements' => [         'factories' => [             'roleselect' => 'mymodule\form\element\roleselectfactory',         ],     ], ]; 

there not need extend standard select class changes configuration only. best done in factory class.

namespace mymodule\form\element;  use zend\form\element\select;  class roleselectfactory {     public function __invoke($formelementmanager, $name, $rname)     {         $select = new select('role_id');          $select->setoptions(['label' => 'role']);         $select->setattributes(['id' => 'role_id']);          $servicemanager = $formelementmanager->getservicelocator();         $roleservice = $servicemanager->get('admin\service\roleservice');          $options = [];         foreach($roleservice->getalltheroles() $role){             $options[$role->getid()] => $role->getname();         }          $select->setvalueoptions($options);          return $select;     } } 

adding element within form can updated use name of service registered.

$this->add([          'name' => 'role_id'     'type' => 'roleselect',        ]); 

one important point remember form using element must created using $formelementmanager->get('formwithroleselect').


Comments

Popular posts from this blog

c - How to retrieve a variable from the Apache configuration inside the module? -

c# - Constructor arguments cannot be passed for interface mocks -

python - malformed header from script index.py Bad header -