I Have been following zf2 guide for blog I have created everything Controller, Factory, Form, Mapper, Model, Service, view etc
In my form I have a 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 this form I want to load the option for the role from the database.
I tried loading the option by creating a simple function, which can be accessed in the element as below, but Am not able to fetch the result. I have already created Controller, Factory, Form, Mapper, Model, Service and view, Where I can do 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 anybody guide me how can I load all the Roles in option as listed in the IndexAction following Blog Post with ID and Name of the Role.
Finally found out the simple way to do this, Am really not sure if this is the correct way.
Added the Role service in the User Controller
Code in my userController.php
My UserControllerFactory.php
Finally the UserForm.php
This way using service manager I was successfully able to load the data in my for Select option.
Call
getAllRoles()
inside the controller then You can pass your custom array as parameter forform
when you createform
object. Inform
__construct function you can retrieve that array and set like thisYou could create a reusable form element that is pre-populated with the roles. To do so you must register the service with the form element manager in
module.config.php
.There is not need to extend the standard select class as the changes are configuration only. This is best done in a factory class.
Adding the element within a form can then be updated to use the name of the service we registered.
One important point to remember is that the form using this element must be created using the
$formElementManager->get('FormWithRoleSelect')
.