I can't insert data in the database. I'm using yii2 advanced.
I have 3 tables: the default user table, post, and category. Each post has one category, and one category can have many posts. But when I click on 'Save' in my create form - nothing happens, the page just refreshes. The post table is still empty.
Here's PostController
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use frontend\models\CreateForm;
use frontend\models\Category;
use yii\helpers\ArrayHelper;
class PostController extends Controller
{
public function actionCreate()
{
if(Yii::$app->user->isGuest)
{
return $this->redirect(['/site/login']);
}
$model = new CreateForm();
$category = Category::find()->all();
$items = ArrayHelper::map($category, 'id', 'name');
if ($model->load(Yii::$app->request->post()))
{
if ($model->save())
{
Yii::$app->session->setFlash(
'success',
true
);
return $this->refresh();
} else
{
Yii::$app->session->setFlash(
'success',
false
);
}
}
return $this->render('create', [
'model' => $model,
'items' => $items
]);
}
This is CreateForm model
namespace frontend\models;
use yii\base\Model;
use frontend\models\Post;
use Yii;
class CreateForm extends Model
{
public $category;
public $title;
public $content;
public function attributeLabels()
{
return [
'category' => 'Category',
'title' => 'Title',
'content' => 'Content',
];
}
public function save()
{
$post = new Post();
$post->user_id = Yii::$app->user->id;
$post->category_id = $this->category;
$post->title = $this->title;
$post->content = $this->content;
$post->created_at = time();
}
}
And this the view
use yii\bootstrap\ActiveForm;
use yii\bootstrap\Html;
$form = ActiveForm::begin();
echo $form->field($model, 'category')->dropDownList($items);
echo $form->field($model, 'title')->textInput();
echo $form->field($model, 'content')->textInput();
echo Html::submitButton('Save', ['class' => 'btn btn-primary']);
ActiveForm::end();
What am I doing wrong, I can't understand
saveinCreateFormis not saving a new post, just assigning the values. You also might add validation rules inCreateForm. Read Creating Forms and Validating Input in the Guide.