Yii2 active record model not saving data

后端 未结 7 663
情话喂你
情话喂你 2020-12-16 17:47

I\'ve built a simple form model & view, a simple AR model, and a simple controller. The form model assigns the correct values to the AR instance, but when I call save(),

7条回答
  •  旧巷少年郎
    2020-12-16 18:09

    How to Troubleshoot

    First thing you should add while developing to your _form.php is errorSummary():

    
    // Some input fields
    ...
    errorSummary($model); ?> // <--- Add this 
    ...
     
    

    Simplify

    Why not use scenarios instead if there is some minimal variation form to form:

    In your model:

        public function rules()
        {
            return [
                [['field_1'], 'required', 'on' => self::SCENARIO_ADD],  // only on add
                [['field_2'], 'required', 'on' => self::SCENARIO_UPDATE], // only on update
                [['field_3', 'field_4'], 'required'], // required all the time
            ];
        }
    

    In your controller:

    public function actionAdd()
    {
        $model = new Model();
        $model->scenario = Model::SCENARIO_ADD;
        if ($model->load(Yii::$app->request->post())) {
            return $this->redirect(['view', 'id' => $model->id]);
        }
    
        return $this->render('add', ['model' => $model]);
    }
    

    Behaviors

    Alternatively, rather than assign the user directly in your model, you could use a behavior like so:

    https://www.yiiframework.com/doc/api/2.0/yii-behaviors-blameablebehavior

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            [
                'class' => \yii\behaviors\BlameableBehavior::className(),
                'value' => Yii::$app->user->identity->username,
            ],
            [
                'class' => \yii\behaviors\TimestampBehavior::className(),
                'value' => new \yii\db\Expression('NOW()'),
            ],
            [
                'class' => 'sammaye\audittrail\LoggableBehavior',
                'userAttribute' => 'updated_by', //blameable attribute of the current model.
                'ignored' => ['updated_by', 'updated_at'], // This ignores fields from a selection of all fields, not needed with allowed
            ],
        ];
    }   
    

提交回复
热议问题