代码之家  ›  专栏  ›  技术社区  ›  breakline

Yii2从表单中删除可选的已创建字段

  •  1
  • breakline  · 技术社区  · 7 年前

    我创建了一个“BTeam”模型类,其属性id为name。我用Gii生成了这个。

    我添加了“TimestampBehavior”,它在模型创建期间用当前时间戳填充“created”字段。

    如何从“添加”页面中删除该字段:

    enter image description here

    我的BTeam课程:

    <?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',
        ];
    }
    }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Nimer    7 年前

    从所述控制器的角度来看,只需将其从\u表单中删除即可。按规定是安全的,所以应该没问题。

        2
  •  0
  •   Gireesh    7 年前

    您还可以将此函数添加到模型中,并使用gii生成CRUD(应用覆盖)

    public  function safeAttributes ( ){
        return [
            'id' ,
            'name' ,
        ];
    }
    

    此方法必须返回在创建/添加页面(由gii生成)中显示字段所需的唯一字段。