Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine date in save override / before save

I have Doctrine model with a date field "date_of_birth" (symfony form date) which is filled in by the user all works 100% it saves to the db as expected, however in the model save() method I need to retrieve the value of this field before save occurs. My problem is that When trying to get the date value it returns empty string if its a new record and the old value if it is an existing record

public function save(Doctrine_Connection $conn = null)
{
      $dob = $this->getDateOfBirth(); // returns empty str if new and old value if existing
      $dob = $this->date_of_birth; //also returns empty str

      return parent::save($conn);
 }

How Can I retrieve the value of this field beore data is saved

like image 941
wikus verreynne Avatar asked Mar 22 '10 09:03

wikus verreynne


2 Answers

In Doctrine 1.2 you can override preSave pseudo-event:

// In your model class
public function preSave($event) {
   $dob = $this->getDateOfBirth();

   //do whatever you need

   parent::preSave($event);
}

In Doctrine 2.1 the function names changed.

like image 113
Benoit Avatar answered Nov 15 '22 09:11

Benoit


Generaly pseudo-events in doctrine uses "new" values, however there is getModified() method and it doing exactly what you need.

$modifiedFields = $this->getModified(true);
if(isset($modifiedFields['date_of_birth'])) { //index is available only after change
  echo $modifiedFields['date_of_birth']; //old value
}

more info from doc about getModified()

like image 21
Mikołaj Kopras Avatar answered Nov 15 '22 11:11

Mikołaj Kopras