Zend Edit表单 - 无法更新现有数据

时间:2014-12-18 11:30:04

标签: php zend-framework zend-form zend-db

我正在尝试为此表单构建一个编辑函数:

class Application_Form_ContactMethodSelected extends Zend_Form{

    public function init()
    { 

        $this->CompanyName = new Zend_Form_Element_Text('CompanyName', array('label' => 'Firma', 'required' => true));

        $this->submit = new Zend_Form_Element_Submit('submit');
        $this->submit->setLabel('Fertig');

        $this->addElements(array($this->CompanyName,$this->submit));

    }
}

这是我的控制者:

class UploadController extends Zend_Controller_Action{   
    protected $clientTable;
    protected $model;
    protected $id;

    public function init(){
        $request = $this->getRequest();
        if ($request->isGet())
        {
            $this->id = (int)$request->getParam('id');
        }
        $this->clientTable = new Application_Model_DbTable_ClientTable();
        $this->model = new Application_Model_DbTable_ClientTable();
        $this->formClient = new Application_Form_ContactMethodSelected();

     }

    public function editAction() 
    {
        if($this->id){
            $results = $this->model->find($this->id);
            $data = array();

            //put results into our data array as name => value

            foreach($results as $r)
            {
                $data['CompanyName'] = $r['CompanyName'];

            }

            //populate  form

            $this->formClient->populate($data);

        }

        if ($this->_request->isPost()) {
            $request = $this->getRequest();
            if ($request->isGet())
            {
                $this->id = (int)$request->getParam('id');
            }

            $client =  $this->clientTable->fetchRow(array('ID' =>$this->id));
            if($this->id){$formClientData = $this->_request->getPost();}

                // write to DB

                $client->CompanyName = $request->getPost('CompanyName');


                //if($results){
               // $where = $this->clientTable->getAdapter()->quoteInto('id = ?',$this->id);
                    //$client->update($client,$where);
                //$this->clientTable->update($client, $where);


                //$this->clientTable->update($data, $where);
                $client->save();

               $this->_redirect('client/index');
                exit;
       }

        $this->view->formClient = $this->formClient;    

    }
}

我可以使用id=0更新我的第一个数据库条目。
但后来我要求/uploadcontroller/edit?id=2我仍在更新id=1

感谢。

1 个答案:

答案 0 :(得分:1)

以下是代码中的错误。

您首先检查请求isPost(),然后再次检查失败的请求isGet()(因为两者都不能一次为真)且您的$this->id变量未获得初始化。 (所以错误的记录更新)

if ($this->_request->isPost()) {
    $request = $this->getRequest();
    if ($request->isGet())
    {
        $this->id = (int)$request->getParam('id');
    }
    .....

删除请求isGet()条件并立即使用id参数。

示例代码:

if ($this->_request->isPost()) {
    $this->id = (int)$this->_request->getParam('id');
    $client =  $this->clientTable->fetchRow(array('ID' =>$this->id));
    .....