Yii2 从表单中删除可选的创建字段
Yii2 remove optional created field from form
我有一个 "BTeam" 模型 class,其属性为 id、name、created。我用 Gii 生成了这个。
我添加了 "TimestampBehavior",它在模型创建期间用当前时间戳填充了 "created" 字段。
如何从 "add" 页面中删除字段:
我的 BTeam class:
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
class BTeam extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'b_team';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name'], 'required'],
[['created'], 'safe'],
[['name'], 'string', 'max' => 200]
];
}
public function behaviors() {
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created']
]
]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'created' => 'Created',
];
}
}
鉴于所述控制器,只需将其从 _form 中删除即可。按规定是安全的,所以应该没问题。
您还可以将此功能添加到模型中并使用 gii 生成 CRUD(应用覆盖)
public function safeAttributes ( ){
return [
'id' ,
'name' ,
];
}
此方法必须 return 在 create/add 页面(由 gii 生成)中显示字段所需的唯一字段。
我有一个 "BTeam" 模型 class,其属性为 id、name、created。我用 Gii 生成了这个。
我添加了 "TimestampBehavior",它在模型创建期间用当前时间戳填充了 "created" 字段。
如何从 "add" 页面中删除字段:
我的 BTeam class:
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
class BTeam extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'b_team';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name'], 'required'],
[['created'], 'safe'],
[['name'], 'string', 'max' => 200]
];
}
public function behaviors() {
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created']
]
]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'created' => 'Created',
];
}
}
鉴于所述控制器,只需将其从 _form 中删除即可。按规定是安全的,所以应该没问题。
您还可以将此功能添加到模型中并使用 gii 生成 CRUD(应用覆盖)
public function safeAttributes ( ){
return [
'id' ,
'name' ,
];
}
此方法必须 return 在 create/add 页面(由 gii 生成)中显示字段所需的唯一字段。