开发者

Does symfony have a built-in method for comparing tainted values to the original?

I am using symfony 1.4 with Doctrine. I have built a form which uses a table that has the Versionable behaviour. As expected, Versionable creates a new version of the row 开发者_C百科every time the form is submitted and saved. My problem is that I would like to prevent it doing so if the actual values submitted are not any different from the original values put into the form via the edit action.

I know that I can do this with javascript relatively easily. I'm just curious as to whether symfony or Doctrine have this functionality already, and how it is used if so. It just seems like something that symfony would have a method for, which could be checked right before $form->save() is called. Am I dreaming or perhaps missing something obvious?


You can use the DoctrineRecord::getModified() function which returns an array of the modified fields and associated values from an overridden save() function or in a listener (preSave would be the best I guess).
If the new values are not any different, you can bypass the actual call to save(), so no new version is created.


The comment for the save() method of the Doctrine_Record is

/**
 * applies the changes made to this object into database
 * this method is smart enough to know if any changes are made
 * and whether to use INSERT or UPDATE statement
 *
 * this method also saves the related components
 *
 * @param Doctrine_Connection $conn     optional connection parameter
 * @throws Exception                    if record is not valid and validation is active
 * @return void
 */

so first, you should check whether it does not already work. If not, Doctrine_Record has a isModified() method you could use. If the bind() method of the form object modifies the object in the form which should at first contain the default values, then this method should return true.


If you don't want to override save() method or implement a listener as jaudette suggested you can instead stay with form binding:

$form->bind($values);
if ($form->isValid()) {
    $form->updateObject();
    $changes = $form->getObject()->getModified();

    // save to database if desired
    $form->save();
}

The object will not be saved to database by calling $form->updateObject(), but the actual php object is changed.
Also note that you might have to call getModified() on each related object if you have embedded subforms.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜