简体   繁体   中英

Zend framework save instead of insert update

I want to use save method to save form data. but when i call save on object its gives following error. It works fine if I call insert method on object. Fatal error: Call to undefined method

Application_Model_Content::save() in /var/www/html/ZendTecAdmin/application/controllers/AdminController.php on line 44

Following is my controller action code

$content  = new Application_Model_Content();
          if($this->_request->getParams('id')){
            $id =  $this->_request->getParams('id');  
            $row = $content->find($id)->toArray();   
            if($row){
            $form->populate($row[0]);
            }
           }

    if ($this->_request->getPost('Publish')) {
                $formData = $this->_request->getPost();           
                if ($form->isValid($formData)) { //If form data is valid  
                    unset($formData['Publish']);                
                    $content->save($formData);
                   //$content->insert($formData); //it works fine
                }
            }

Following is my model

<?php
class Application_Model_Content extends Zend_Db_Table
{
   protected $_name = "content";

}

Please help me to get it resolve.

You can get Row object and use save() on it:

$select = $content->select()->where('id = ?',$id);
$row = $content->fetchRow($select);
$row->name = 'John'
$row->birthdate = 1980-11-04;
$row->save();

To extend Row Class you can add protected $_rowClass = 'Application_Model_Row_User'; to your Model and then you create class Application_Model_Row_User extends Zend_Db_Table_Row_Abstract . Now you can add your own methods to this class like this :

public function dateToAge(){
    return (int)floor( (strtotime(date('Y-m-d')) - strtotime($this->birthdate)) / 31556926);
}

and later:

$select = $content->select()->where('id = ?',$id);
$row = $content->fetchRow($select);
$name = $row->name
$age = $row->dateToAge();

You can read more here: http://framework.zend.com/manual/1.12/en/zend.db.table.row.html

It works fine if write code in model content as below

<?php

class Application_Model_Content extends Zend_Db_Table {

    protected $_name = "content";

    function save($data) {

        if (null === ($id = $data['id'])) {
            unset($data['id']);
            $this->insert($data);
        } else {
            $this->update($data, array('id = ?' => $id));
        }
    }

}

Is there any other standard way to do this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM