【问题标题】:How do I update a value (adding on to that value) on every form submit?如何更新每个表单提交的值(添加到该值)?
【发布时间】:2021-10-26 05:46:26
【问题描述】:

我有一个交易表单,提交时会存储一个“total_value”。然后页面重新加载到相同的表单上,以便用户可以添加更多数据。我希望将输入的值添加到之前插入的“total_value”中。

示例: 如果第一次提交值 = 10,第二次提交值 = 5,则存储的 total_value 应为 15。

这是我在控制器中的代码:

$discount = Master::findOne(['id' => $usrM->master_id])->rate_discount;
$tempArray = Yii::$app->request->post('template');
$seat = Yii::$app->request->post('BookingDetails')['seats_count'];
$cost = [];

if ($model->load(Yii::$app->request->post())) {

       $sp = Template::findOne(['id'=>$tempArray])->standard_price;
       $seat_cost = $sp * $seat;
       array_push($cost, $seat_cost);
       $sum = array_sum($cost);

       //this is the total cost of all templates with master center discount applied
       $total = $sum - ($sum*($discount/100));

       $model->save();
       Yii::$app->db->createCommand('UPDATE ebs_booking_transaction SET total_value ='.$total.' WHERE id = '.$trans)->execute();

【问题讨论】:

  • SET total_value = total_value + ...

标签: php arrays session yii2


【解决方案1】:

例如,您可以使用 Yii2 的 ActiveRecord beforeUpdate 内置方法和非常方便的属性 dirtyAttributes 来始终更新 total_value 每当发生更新事件并且 total 值在该更新事件中发生更改。

另见: Yii2 before save check if attributes are changed

还有:https://www.yiiframework.com/doc/guide/2.0/en/db-active-record#dirty-attributes

【讨论】:

    猜你喜欢
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    相关资源
    最近更新 更多