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


Zend Edit form - Cant update existing data

我正在尝试为这种形式构建一个编辑函数:

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.

谢谢。

这是代码中的错误。

您首先检查请求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));
    .....