2011-04-14 25 views
1

我正在編寫一個symfony 1.4應用程序,並試圖設置將在編輯對象時特定值發生更改時運行的代碼。如何獲得symfony保存方法內的原始值?

我想在模型類內部而不是在視圖內部執行此操作,因爲無論何時保存此對象,此操作都會生效。

在用戶做出任何更改之前,有沒有辦法訪問對象的原始值?

注:

的對象尚未保存,因此它仍然是可能的(不知何故)檢索原始值。

CODE:

public function save() 
{ 
    if($this->isNew()) 
     $this->getAcctRelatedByAccountId()->updateCurrentBalance(($this->isAdditive()) ? $this->getAmount(): $this->getAmount()*-1); 

    // get the original value HERE 

    // do work based on the original value 

    // do work based on the new, submitted value 

    return parent::save(); 
} 

回答

2

如果您不需要計算進行保存時做的,覆蓋列的設置者。

只要設置了值,就可以根據原始值進行計算,然後在新值上進行計算,最後調用覆蓋的父設置器來實際設置新值。

0

你可能得到這樣的值:$this->_get('field'); (_set('field', value)) ?

或者你可以使用的doctrine event listeners

+0

我的項目是使用Propel,有沒有類似的東西? – Patrick 2011-04-14 03:58:10

+0

哦,我不知道。我對Propel ORM知之甚少。 – cuhuak 2011-04-18 06:22:50

0

我對類似問題的方法:

/** 
* Returns Record's original values before saving the new ones 
* 
* @return array 
*/ 
public function getOldValues() 
{ 
    $arr_modified = $this->getModified(true); 
    $arr = $this->toArray(false); 

    foreach ($arr_modified as $k => $v) 
    { 
     $arr[$k] = $v; 
    } 

    return $arr; 
} 



/** 
* Sample usage of getOldValues 
* 
* @param Doctrine_Connection $conn 
*/ 
public function save(Doctrine_Connection $conn = null) 
{ 
    $dispatcher = ProjectConfiguration::getActive()->getEventDispatcher(); 

    /* object values before saving */ 
    $arr_before = $this->getOldValues(); 

    $event_name = 'myobject.update'; 
    if (true == $this->isNew()) 
    { 
     $event_name = 'myobject.add'; 
    } 

    parent::save($conn); 

    /* object values after saving */ 
    $arr_after = $this->toArray(true); 

    /* Notify about the record changes */ 
    if ($dispatcher instanceof sfEventDispatcher) 
    { 
     $dispatcher->notify(new sfEvent($this, $event_name, array('before' => $arr_before, 'after' => $arr_after))); 
    } 
} 
0

你可以做到這一點通過重寫processForm()。在行動從緩存中獲取它,你可以:

$form->getObject() ; //the original object 
$request->getParameter($form->getName()) ; // the new object 
相關問題