从zf2表单的其他表中选择元素

时间:2013-07-31 12:43:10

标签: php zend-framework2 zend-form

我在客户端和销售之间的数据库上有2个具有ManyToOne关系的表,我想在销售表单上选择id_client。因为那个使用了那个。

SaleForm:

public function __construct(ClientTable $table)
    {
        parent::__construct('vente');

        $this->setAttribute('method', 'post');
        $this->clientTable = $table;     
        $this->add(array(
            'name' => 'id',
            'attributes' => array(
                'type'  => 'hidden',
            ),
        ));
        $this->add(
                array(
                    'name' => 'id_client',
                    'type' => 'Select',
                    'attributes' => array(
                        'id'    => 'id_client'
                    ),
                    'options' => array(
                        'label' => 'Catégory',
                        'value_options' => $this->getClientOptions(),
                        'empty_option'  => '--- Sélectionnez une categorie---'
                    ),
                )
            );
         public function getClientOptions()
        {
            $data  = $this->clientTable->fetchAll()->toArray();
            $selectData = array();

            foreach ($data as $key => $selectOption) {
                $selectData[$selectOption["id"]] = $selectOption["nom_client"];
            }

            return $selectData;
        }
}

SaleController:

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Caisse\Model\Sale;          
use Caisse\Form\SaleForm; 

class SaleController extends AbstractActionController
{
    protected $saleTable;
    protected $clientTable;

    public function addAction()
    {
        $form = new SaleForm($this->clientTable);
        $form->get('submit')->setValue('Ajouter');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $vente = new Sale();
            $form->setInputFilter($sale->getInputFilter());
            $form->setData($request->getPost());

            if ($form->isValid()) {
                $vente->exchangeArray($form->getData());
                $this->getSaleTable()->saveSale($sale);


                return $this->redirect()->toRoute('sale');
            }
        }
        return array('form' => $form);

    }
}

但每次我遇到这个问题:

  

可捕获的致命错误:参数1传递给   Caisse \ Form \ SaleForm :: __ construct()必须是。的实例   Admin \ Model \ ClientTable,null给出。

这是一个很好的方法,欢迎任何参考相同的例子。

谢谢

1 个答案:

答案 0 :(得分:1)

在你的控制器中,运行 addAction ,你永远不会设置变量 clientTable ,也许你忘了初始化它。

喜欢这个

public function addAction()
{
    $this->clientTable = $this->getServiceLocator()->get('Client\Model\ClientTable');
    $form = new SaleForm($this->clientTable);
    // ...
}

关于

    public function getClientOptions()
    {
        $data  = $this->clientTable->fetchAll();
        $selectData = array();

        foreach ($data as $row) {
            $selectData[$row->id] = $row->nom_client;
        }

        return $selectData;
    }