我使用 rand() 函数在我的应用程序中生成booking_id
,它在创建预订记录时生成随机字符串。但是当我更新特定记录时,booking_id
也会更新为一些随机字符串。如何在更新记录时停止生成随机数。
<?= Html::activeHiddenInput($model, 'booking_id', ['value' => rand('100000',10) ]) ?>
使用行为来设置预订ID,例如在此示例中,使用您的兰特值设置booking_id
,这仅适用于插入事件,因此更新booking_id
将保持不变。
将行为代码添加到模型中(或使用它扩展现有行为):
namespace app'models'base; // or whatever your namespace is.
use yii'behaviors'AttributeBehavior; // must be added to the use part to include the correct class.
use yii'db'ActiveRecord;
class Yourclass extends ActiveRecord
{
...
public function behaviors()
{
return [
[
'class' => AttributeBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['booking_id'],
],
'value' => function ($event) {
return rand('100000',10);
},
],
];
}
...
}
并且不要使用表单中的隐藏字段。可以修改 Html 代码,因此隐藏字段不安全以防止用户修改。