2014-01-06 134 views
2

這可能很簡單,但我是新手。從控制器發送數據在zend框架中查看2

我想寫一個簡單的帖子&類別系統。我創建了一個類別模塊,並且還創建了發佈模塊。

我想添加selectbox來選擇這個addpost頁面的哪個類別。我不知道如何。誰能幫我?

+1

看看這個教程http://stackoverflow.com/a/18288420/949273它的[傳遞價值,以查看在ZF2 – tasmaniski

+0

可能重複的封面基本Zend Framework 2](http://stackoverflow.com/questions/15331792/passing-values-to-view-in-zend-framework-2) – Ankur

回答

1

你只需要將結果集註入到表單中,並創建一個數組,並將其傳遞給選擇的選項。

<?php 
namespace Mylib\Controller; 

use Zend\Mvc\Controller\AbstractActionController; 
use Mylib\Form\MyForm; 

class MyControler extends AbstractActionController 
{ 
    private $myObjectTable; 

    public function getMyObjectTable(){ 
     if(!$this->myObjectTable){ 
      $this->myObjectTable = $this->getServiceLocator() 
       ->get('MyLib\Model\MyObjectTable'); 
     } 
    } 

    public function indexAction(){ 
     $objects = $this->getMyObjectTable()->fetchall(); 

     $form = new MyForm($objects); 

     $filter = new MyFormFilter(); 
     $form->setInputFilter($filter->getInputFilter()); 

     $form->setData($request->getPost()); 
     if($form->isValid()){ 
      // [...] here the post treatment 
     } 
     return array('form' =>$form); 
    } 
} 

,並在您的形式:

<?php 
namespace Mylib\Form; 

class MyForm 
{ 
    public function __construct($objects){ 
     $selectOptions = array(); 
     foreach ($objects as $object) { 
      $selectOptions[$object->id]=$object->thePropertyIWantToList; 
     } 
     $this->add(array(
      'name' => 'object_id', 
      'type' => 'Select', 
      'options' => array(
       'value_options' => $selectOptions, 
       'label' => 'MySelectBoxLabel', 
      ) 
      'attributes' => array(
       'value' => 9, // to select a default value 
      ) 
     )); 
     //and the rest of the form... 
     $this->add(array(
      'name' => 'submit', 
      'type' => 'Submit', 
      'attributes' => array(
       'id' => 'submitbutton', 
       'value' => 'Go', 
      ), 
     )); 
    } 
}