2014-01-06 161 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', 
      ), 
     )); 
    } 
}