Doctrine listener - run action only if a field has changed

吃可爱长大的小学妹 提交于 2019-12-20 09:23:47

问题


How do I check if field has changed?

I'd like to trigger an action in preSave() only if specific field has changed, e.q.

public function preSave() {
    if ($bodyBefore != $bodyNow) {
         $this->html = $this->_htmlify($bodyNow);
    }
} 

The question is how to get this $bodyBefore and $bodyNow


回答1:


Please don't fetch the database again! This works for Doctrine 1.2, I haven't tested lower versions.

// in your model class
public function preSave($event) {
  if (!$this->isModified())
    return;

  $modifiedFields = $this->getModified();
  if (array_key_exists('title', $modifiedFields)) {
    // your code
  }
}

Check out the documentation, too.




回答2:


Travis's answer was almost right, because the problem is that the object is overwritten when you do the Doctrine query. So the solution is:

public function preSave($event)
{
  // Change the attribute to not overwrite the object
  $oDoctrineManager = Doctrine_Manager::getInstance(); 
  $oDoctrineManager->setAttribute(Doctrine::ATTR_HYDRATE_OVERWRITE, false); 

  $newRecord = $event->getInvoker();
  $oldRecord = $this->getTable()->find($id);

  if ($oldRecord['title'] != $newRecord->title)
  {
    ...
  }
}



回答3:


Try this out.

public function preSave($event)
{
   $id = $event->getInvoker()->id;
   $currentRecord = $this->getTable()->find($id);

   if ($currentRecord->body != $event->getInvoker()->body)
   {
      $event->getEnvoker()->body = $this->_htmlify($event->getEnvoker()->body);
   }   
}


来源:https://stackoverflow.com/questions/2059399/doctrine-listener-run-action-only-if-a-field-has-changed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!