Skip to content
Advertisement

Can’t insert into database with save()

I am having an issue inserting a record into the database. I am a beginner with the Yii framework, so I may have made some stupid mistakes.

This is from the SiteController

public function actionCreatePost(){
     $model = new PostForm();

     $post = new Post();

    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        $post->body = $model->body;
        $post->title = $model->title;
        $post->save();

        return $this->redirect('index');
    }else {
        return $this->render('createPost', ['model' => $model]);
    }
}

This is from the Post class

public function behaviors()
{
    return [
        [
            'class' => TimestampBehavior::className(),
            'createdAtAttribute' => 'created_at',
            'updatedAtAttribute' => 'updated_at',
            'value' => new Expression('NOW()'),
        ],
        [
            'class' => BlameableBehavior::className(),
            'createdByAttribute' => 'id_author',
        ]
    ];
}

Advertisement

Answer

The issue is that you have created a PostForm class for the form (which is correct) but you are then trying to load the response into the Post class – a completely different class. This won’t work without modification.

If you have a look at the response:

var_dump(Yii:$app->request->post()); 

You will see the form data is located within the PostForm key. Yii will therefore only load the data into the PostForm class.

The correct solution is therefore to create a savePost() function within the PostForm eg:

public function savePost(){
$model = new Post();
$model->propertyABC = $this->propertyABC
...etc...
$model->save();

So the action would appear as follows:

$model = new PostForm();
If($model->load(Yii::$app->request->post()) && $model->validate()){
$model->savePost();

The other option is to rename the key from PostForm to Post. Yii will then load the data but this is not the best approach as it is a bit obscure.

Hope that helps

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement