R – Saving row after populating from Array – Zend

zend-dbzend-db-tablezend-framework

Once again a Zend Framework question! Any help is appreciated.

I have a DB table class which i want to use to insert/update rows when a form is posted, and i would like to use the save() method so it can all go through the same method.


//Users Db Table class
class DBTables_Users extends Zend_Db_Table_Abstract
{
    protected $_name = "users";
    protected $_primary = "userID";
}

So here is my test code…


$userArray = array( 'userID' => 1,
      'firstName' => 'Test',
      'lastName' => 'Test',
      'emailAddress' => 'test@hotmail.com'
      );

$user = new DBTables_Users();

$newUserRow = $user->createRow($userArray);

$newUserRow->save();

This works perfectly without the "userID" item and inserts fine, but if i add that in it tries to insert it again and errors with a duplicate key error.

To me the row should acknowledge the presence of the primary key and use it as the where clause to update the row. However after delving into the code the only thing that it checks, to determine whether its an insert or update, is the presence of the "_cleanData" variable which is populated on construction if the config has a "data" option which it doesnt when using the createRow method.

Am i going about this the wrong way or does it need an ugly fix of setting the _cleanData property myself in an override?

Cheers
Stuart

Best Answer

Surely if the entry is a new one you wont have an ID being passed from your form?

Can't you do a quick check if that is null or empty then call an insert rather than the update?

Don't try and do too many things with one method, if they do a different task seperate them out.

Heres an example of my insert / update methods situated in a class which extends Zend_Db_Table (Zend Framework 1.8)

public function insertQuote($quote)
    {
        $data = array('id'=>null,'quote'=>$quote, 'dateCreated'=>NOW());
        $id = $this->insert($data);

        return $id;
    }

public function updateQuote($id, $quote)
    {
        $data = array(
        'quote'=>$quote
        );
        $this->update($data, 'id = ' . (int)$id);
    }
Related Topic