所以我试图通过Yii2表单获取信息并将其保存到数据库中,尽管它不会起作用。我收到了成功的flash消息,但没有对数据库进行任何更改。
控制器文件:
<?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
]);
}
}
这将是View文件:
<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>
答案 0 :(得分:2)
更改您的索引操作
$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
]);
}
答案 1 :(得分:1)
很可能您的模型未通过验证。你可以使用if (!$form_model->validate()) {
return $this->render('index', [
'form_model' => $form_model
]);
}
关闭,但最好知道它为什么没有验证。这样做:
List<Database.tblProduct> Lst=new List<Database.tblProduct>;
答案 2 :(得分:0)
好的,所以我找到了解决方案:$ model-&gt; save(false) - 没有任何验证。将来会尝试整理验证规则。