P
P
prozrost2017-10-04 09:54:53
Yii
prozrost, 2017-10-04 09:54:53

Why is the data not saved?

I want to save the data that came from the form, here is the method in the controller

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

and the model itself:
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 getComments()
    {
        return $this->hasMany(Comment::className(), ['post_id' => 'id']);
    }
    public function getUser()
    {
        return $this->hasOne(User::className(),['id' => 'user_id']);
    }
}

But now, when submitting the form, only created_at, user_id and that's it. That is those fields which I set explicitly. What's wrong?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
Anton, 2017-10-04
@karminski

Why explicit declaration of attributes in a model? Remove all public attributes.

D
Dmitry, 2017-10-04
@slo_nik

Good morning.
Add a method to the model

public function behaviors()
{
     return [
       TimestampBehavior::className()
    ];
}

Remove in controller
Replace
with
And at the beginning of the controller, add and remove the slash before Yii everywhere. What other fields are you passing? The image may not pass validation, so it is not saved. Highlight all the code that is responsible for loading the image into a separate model.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question