【问题标题】:how to get the original value inside the symfony save method?如何在 symfony 保存方法中获取原始值?
【发布时间】:2011-04-14 01:32:19
【问题描述】:

我正在编写一个 symfony 1.4 应用程序,并试图设置在编辑对象时特定值发生变化时运行的代码。

我试图在模型类中而不是在视图中执行此操作,因为这将在保存此对象时应用。

有没有办法在用户进行任何更改之前访问对象的原始值?

注意:

对象尚未保存,因此仍然可以(以某种方式)检索原始值。

代码:

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();
}

【问题讨论】:

    标签: php symfony1 symfony-1.4 overloading


    【解决方案1】:

    如果保存时不需要进行计算,请覆盖该列的设置器。

    每当设置一个值时,你可以根据原始值进行计算,然后在新的值上,最后调用被覆盖的父设置器来实际设置新值。

    【讨论】:

      【解决方案2】:

      你可能会得到这样的价值:$this->_get('field'); (_set('field', value)) ?

      或者你可以使用doctrine event listeners

      【讨论】:

      • 我的项目用的是Propel,有没有类似的?
      • 哦,我不知道。我对 Propel ORM 知之甚少。
      【解决方案3】:

      我对类似问题的处理方法:

      /**
       * 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)));
          }
      }
      

      【讨论】:

        【解决方案4】:

        您可以通过覆盖processForm() 来做到这一点。在操作中从缓存中获取它,您可以:

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

        【讨论】:

          猜你喜欢
          • 2011-04-25
          • 2023-04-11
          • 1970-01-01
          • 1970-01-01
          • 2023-03-24
          • 2011-01-09
          • 2011-01-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多