【问题标题】:Yii2 Behaviors / Scenarios Modify AttributeYii2 行为/场景修改属性
【发布时间】:2015-09-22 03:57:35
【问题描述】:

我有一个模型“Product”,我想修改或“改变”它的一个属性,但仅限于特定情况。

我将属性 price 存储为整数。所以 1.99 美元存储为 199。

我想将它与 activeForm 结合起来,这样当获得价格时,它会在现场(视觉上)转换为“1.99”。但是当我提交表单时,在验证之前,它会将价格从“1.99”修改为“199”。

我假设这将需要行为,并在创建活动表单之前专门将行为附加到模型。但是,我仍然对如何设置它感到困惑。我看到有一个 AttributeBehavior 类,或者我可以制作自己的 Behavior 类,但在这种情况下我一直无法弄清楚实现。

情况:

foreach ($store_item->storeProducts as $i=>$product) {
?>
 <tr>
     <td>
       <?= $form->field($product, '['.$i.']price')->label(false); ?>
     </td>
 </tr>
 <?php 
    $i++;
  }
 ?>

【问题讨论】:

  • 您可以使用模型事件 beforeValidate() 将 $1.99 存储为 199,当获取结果时您可以使用 afterFind() 将 199 转换为 1.99
  • 数据库字段的类型为int而不是decimal是否有特殊原因?
  • 你可以简单地使用 getter/setter
  • 是的 beforeVaidate() 和 afterFind() 很好,但我不想一直这样做。我只希望在使用此表单时发生这种情况。所以我需要通过一个条件。另一个需要注意的是,模型已经加载到数组中,并且表单处于 for 循环中,因为我一次更新了很多东西。 @topher 回答你的问题。在处理货币转换为 int 时更简洁(Stripe 就是这样做的)。
  • 我给出了一个通用的例子。修改它以满足您的需求

标签: yii2 behavior scenarios


【解决方案1】:

这是我在保存之前检查空属性并赋值的场景。注意owner 返回模型,以便您可以访问公开的模型属性和函数。让我知道是否可以进一步解释

public function behaviors()
{
    return [   
        [
            'class' => AttributeBehavior::className(),
            'attributes' => [
                ActiveRecord::EVENT_BEFORE_INSERT => 'yourAttrib', 
            ],
            'value' => function ($event) { 
                $code = "N/A";
                if(!empty($this->owner->yourAttrib))
                {
                    $code = $this->owner->yourAttrib; //here change your attribute accordingly
                }
                return $code;
            },
        ], 
        //other behaviors
    ];
}

【讨论】:

    【解决方案2】:

    您可以简单地使用 getter/setter,例如:

    public function getRealPrice()
    {
        return $this->price/100;
    }
    
    public function setRealPrice($value)
    {
        $this->price = $value*100;
    }
    

    别忘了:

    • 在模型规则中添加realPrice
    • 在您的表单中使用realPrice(而不是price)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多