Reputation: 315
So I'm trying to get information through a Yii2 form and save it into the database, though it won't work. I'm getting the success flash message, but no changes are made into the database.
Controller file:
<?php
namespace frontend\modules\portfolio\controllers;
use Yii;
use yii\web\Controller;
use frontend\modules\portfolio\models\LandingPage;
use common\models\HelloMessage;
class HelloController extends Controller {
public function actionIndex() {
$form_model = new HelloMessage();
$request = Yii::$app->request;
if ($form_model->load(Yii::$app->request->post())) {
$form_model->name = $request->post('name');
$form_model->email = $request->post('email');
$form_model->message = $request->post('message');
$form_model->save();
Yii::$app->getSession()->setFlash('success', 'Your message has been successfully recorded.');
}
return $this->render('index', [
'form_model' => $form_model
]);
}
}
And this would be the View file:
<div class="box">
<?= Yii::$app->session->getFlash('success'); ?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($form_model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($form_model, 'email')->textInput(['maxlength' => true]) ?>
<?= $form->field($form_model, 'message')->textarea(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['name' => 'contact-button']); ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Upvotes: 1
Views: 6523
Reputation: 3990
Most likely your model fails validation. You can turn if off using $form_model->save(false)
, but it is better to know why it is not validating. Do this:
if (!$form_model->validate()) {
return $this->render('index', [
'form_model' => $form_model
]);
}
Upvotes: 1
Reputation: 315
Ok, so I've found the solution: $model->save(false) - without any validation. Will try to sort out the validation rules in the future.
Upvotes: 0
Reputation: 1035
change your index action like that
$form_model = new HelloMessage();
$postData = Yii::$app->request->post();
if ($form_model->load($postData)) {
if (!$form_model->save())
print_r($form_model->getErrors()); // this would be helpful to find problem.
else
Yii::$app->getSession()->setFlash('success', 'Your message has been successfully recorded.');
}
return $this->render('index', [
'form_model' => $form_model
]);
}
Upvotes: 2