Yii2 行为/场景修改属性

Yii2 Behaviors / Scenarios Modify Attribute

我有一个模型“Product”,我想修改它或 "mutate" 它的一个属性,但仅限于特定实例。

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

我想将其与 activeForm 合并,这样当获取价格时它会在字段中(视觉上)转换为“1.99”。但是当我提交表单时,在验证之前,它会将价格从“1.99”修改为“199”。

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

情况:

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

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

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
    ];
}

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

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

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

别忘了:

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