Rosti
Rosti

Reputation: 161

Why data doesn't save?

I want to handle form and save data from form do my db. I want to get some data from form and another data before saving(like current user_id, current datetime). I've created method in Controller:

public function actionCreate()
    {
        $model = new Post();
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $model->user_id = \Yii::$app->user->getId();
            $model->created_at = \Yii::$app->formatter->asDate(new \DateTime(),'php:Y-m-d');
            $model->image = UploadedFile::getInstance($model, 'image');
            if($model->upload()) {
                $model->image = ('web/images/' . $model->image->baseName . '.' . $model->image->extension);
            } else {
                $model->image = 0;
            }
            $model->save();
            return $this->redirect(['site/blog']);
        } else {
            return $this->render('blog/create', ['model' => $model]);
        }
    }

and my Post model:

class Post extends ActiveRecord
{
    public $title;
    public $text;
    public $image;
    public $comments;

    public function rules()
    {
        return [
            [['title', 'text'], 'required'],
            [['image'], 'file',  'extensions' => 'png, jpg'],
        ];
    }
    public function upload()
    {
        if ($this->image->saveAs(\Yii::getAlias('@app') .'\web\images\\' . $this->image->baseName . '.' . $this->image->extension))
            return true;
        else {
            return false;
        }
    }
    public function getUser()
    {
        return $this->hasOne(User::className(),['id' => 'user_id']);
    }
}

but now when I send my form only user_id,created_at, saved in my db. What I did wrong?

Upvotes: 0

Views: 63

Answers (1)

Yupik
Yupik

Reputation: 5031

Remove this:

public $title;
public $text;
public $image;
public $comments;

From your model. That's all. ActiveRecord is automatically mapping columns from your table.

Upvotes: 2

Related Questions