簡體   English   中英

如何從zf2中的數據庫加載選擇選項

[英]How to load select option from database in zf2

我一直在遵循zf2 博客指南,創建了控制器,工廠,表單,映射器,模型,服務,視圖等所有內容

在我的表單中,我有一個選擇元素

$this->add(array(     
  'type' => 'select',       
  'name' => 'roleId',
  'attributes' =>  array(
    'id' => 'roleId',
    'options' => array(
        '1' => 'Admin',
        '2' => 'Manager',
    ),
  ),
  'options' => array(
    'label' => 'Role',
  ),
));

現在以這種形式,我想從數據庫中加載角色的選項。
我嘗試通過創建一個簡單的函數來加載該選項,該函數可以在下面的元素中進行訪問,但無法獲取結果。 我已經創建了Controller,Factory,Form,Mapper,Model,Service和View,可以在Role上執行CRUD操作。

$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;
}

任何人都可以指導我如何在博客文章后以ID和角色名稱加載IndexAction中列出的所有Roles in選項。

您可以創建一個預填充有角色的可重用表單元素。 為此,您必須在module.config.php向表單元素管理器注冊該服務。

return [
    'form_elements' => [
        'factories' => [
            'RoleSelect' => 'MyModule\Form\Element\RoleSelectFactory',
        ],
    ],
];

由於更改僅是配置,因此不需要擴展標准的選擇類。 最好在工廠課堂上完成。

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() as $role){
            $options[$role->getId()] => $role->getName();
        }

        $select->setValueOptions($options);

        return $select;
    }
}

然后可以更新在表單中添加元素以使用我們注冊的服務的名稱。

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

要記住的重要一點是,必須使用$formElementManager->get('FormWithRoleSelect')創建使用此元素的表單

終於找到了執行此操作的簡單方法,我真的不確定這是否是正確的方法。

在用戶控制器中添加了角色服務

我的userController.php中的代碼

use Admin\Service\RoleServiceInterface;
class UserController extends AbstractActionController
{
  /**
  * @var \Admin\Service\UserServiceInterface
  */
  protected $userService;
  protected $roleService;
  protected $userForm;

  public function __construct(
    UserServiceInterface $userService,
    RoleServiceInterface $roleService,
    FormInterface $userForm
  )
  {
    $this->userService = $userService;
    $this->roleService = $roleService;
    $this->userForm    = $userForm;
  }

  public function addAction()
  {
    $request = $this->getRequest();
    $roles    = $this->roleService->findAllRoles();
    foreach ($roles as $role) {
      if($role->getStatus() == 1) {
        $allRoles[$role->getId()] = $role->getName();
      }
    }
    $this->userForm->__construct(null, array('roleOptions'=>$allRoles));
  }
}

我的UserControllerFactory.php

<?php

namespace Admin\Factory;

use Admin\Controller\UserController;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class UserControllerFactory implements FactoryInterface
{
  /**
  * Create service
  *
  * @param ServiceLocatorInterface $serviceLocator
  *
  * @return mixed
  */
  public function createService(ServiceLocatorInterface $serviceLocator)
  {
    $realServiceLocator = $serviceLocator->getServiceLocator();
    $userService        = $realServiceLocator->get('Admin\Service\UserServiceInterface');
    $roleService        = $realServiceLocator->get('Admin\Service\RoleServiceInterface');
    $userInsertForm     = $realServiceLocator->get('FormElementManager')->get('Admin\Form\UserForm');

    return new UserController(
    $userService,
    $roleService,
    $userInsertForm
    );
  }
}

最后是UserForm.php

<?php

namespace Admin\Form;

use Zend\Form\Form;
use Admin\Model\User;
use Zend\Stdlib\Hydrator\ClassMethods;
use Zend\Form\Element\Select;


class UserForm extends Form
{
  public function __construct($name = null, $options = array())
  {
    $roleOptions = array();
    if($options) {
      $roleOptions = $options['roleOptions'];
    }
    parent::__construct($name, $options);

    $this->setHydrator(new ClassMethods(false));
    $this->setObject(new User());
    $this->add(array(
      'type' => 'hidden',
      'name' => 'id'
    ));

   $this->add(array(     
     'type' => 'select',       
     'name' => 'roleId',
     'attributes' =>  array(
       'id' => 'roleId',
       'options' => $roleOptions
     ),
    'options' => array(
      'label' => 'Role',
    ),
    ));
  }
}

通過使用服務管理器,我可以成功地將數據加載到我的“選擇”選項中。

在控制器內部調用getAllRoles() ,然后在創建form對象時可以將自定義數組作為form參數傳遞。 form __construct函數中,您可以檢索該數組並像這樣進行設置

'options'=> $ roles,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM