Answer the question
In order to leave comments, you need to log in
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>
}
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']);
}
}
Answer the question
In order to leave comments, you need to log in
Why explicit declaration of attributes in a model? Remove all public attributes.
Good morning.
Add a method to the model
public function behaviors()
{
return [
TimestampBehavior::className()
];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question