【问题标题】:In symfony, how to set the value of a form field?在symfony中,如何设置表单域的值?
【发布时间】:2010-11-05 00:05:51
【问题描述】:

我重写了我的 doSave() 方法以基本上执行以下操作:我有一个 sfWidgetFormPropelChoice 字段,用户可以从中进行选择,也可以键入一个新选项。如何更改小部件的值?或者,也许我以错误的方式接近这个问题。所以这就是我如何覆盖 doSave() 方法:

public function doSave($con = null)
{
    // Save the manufacturer as either new or existing.
    $manufacturer_obj = ManufacturerPeer::retrieveByName($this['manufacturer_id']->getValue());
    if (!empty($manufacturer_obj))
    {
        $this->getObject()->setManufacturerId($manufacturer_obj->getId()); // NEED TO CHANGE THIS TO UPDATE WIDGET'S VALUE INSTEAD?
    }
    else
    {
        $new = new Manufacturer();
        $new->setName($this['manufacturer_id']->getValue());
        $new->save();
        $this->getObject()->setManufacturerId($new->getId()); // NEED TO CHANGE THIS TO UPDATE WIDGET'S VALUE INSTEAD?
    }

    parent::doSave($con);
}

【问题讨论】:

    标签: php mysql symfony1 propel


    【解决方案1】:

    您应该使用 setDefault 或 setDefaults,然后它会自动填充绑定的值。

    (sfForm) setDefault ($name, $default)
    (sfForm) setDefaults ($defaults)
    

    用法

    $form->setDefault('WidgetName', 'Value');
    $form->setDefaults(array(
        'WidgetName' => 'Value',
    ));
    

    【讨论】:

      【解决方案2】:

      你可以在行动中做到这一点:

      $this->form->getObject()->setFooId($this->foo->getId()) /*Or get the manufacturer id or name from request here */
      $this->form->save();
      

      但我更喜欢直接在我的 Peer 中与制造商一起做那种工作,所以我的业务逻辑总是在同一个地方。

      我在表单中输入的主要是验证逻辑。

      在 Peer 的 save 方法中放入的示例:

      public function save(PropelPDO $con= null)
      {
        if ($this->isNew() && !$this->getFooId())
        {
          $foo= new Foo();
          $foo->setBar('bar');
          $this->setFoo($foo);
         } 
      }
      

      【讨论】:

      • 感谢您的回复!你将如何在同行中完成这项工作?既然是形式相关的,那不应该是形式吗?对等体没有 ID 或新名称的表单数据。
      【解决方案3】:

      这里有两个假设:a)您的表单获取制造商的名称,b)您的模型需要制造商的 ID

      public function doSave($con = null)
      {
          // retrieve the object from the DB or create it
          $manufacturerName = $this->values['manufacturer_id'];
          $manufacturer = ManufacturerPeer::retrieveByName($manufacturerName);
          if(!$manufacturer instanceof Manufacturer)
          {
              $manufacturer = new Manufacturer();
              $manufacturer->setName($manufacturerName);
              $manufacturer->save();
          }
      
          // overwrite the field value and let the form do the real work
          $this->values['manufacturer_id'] = $manufacturer->getId();
      
          parent::doSave($con);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-25
        • 2019-01-26
        • 2014-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-04
        • 1970-01-01
        相关资源
        最近更新 更多