2
我已經使用Yii2做了web應用程序,表單中提交的值沒有保存在數據庫中。我只是用模型+控制器+視圖structure.Actually形式Mysql數據庫被提交,但是當我參觀了數據庫我只能看到空值的所有條目Yii2表單提交的數據值沒有保存在數據庫中
SiteController.php
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use app\models\CanForm;
use app\models\UploadForm;
use yii\web\UploadedFile;
class SiteController extends Controller
{
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post())) {
$model->name = $_POST['ContactForm']['name'];
$model->email = $_POST['ContactForm']['email'];
$model->subject = $_POST['ContactForm']['subject'];
$model->body = $_POST['ContactForm']['body'];
if ($model->save())
Yii::$app->response->redirect(array('site/contact', 'model' => $model));
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
}
}
Model:ContactForm.php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
/**
* ContactForm is the model behind the contact form.
*/
class ContactForm extends \yii\db\ActiveRecord
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
// name, email, subject and body are required
[['name', 'email', 'subject', 'body'], 'required'],
// email has to be a valid email address
['email', 'email'],
// verifyCode needs to be entered correctly
['verifyCode', 'captcha'],
];
}
/**
* @return array customized attribute labels
*/
public function attributeLabels()
{
return [
'verifyCode' => 'Verification Code',
];
}
/**
* Sends an email to the specified email address using the information collected by this model.
* @param string $email the target email address
* @return boolean whether the model passes validation
*/
public function contact($email)
{
if ($this->validate()) {
Yii::$app->mailer->compose()
->setTo($email)
->setFrom([$this->email => $this->name])
->setSubject($this->subject)
->setTextBody($this->body)
->send();
return true;
} else {
return false;
}
}
}
View:contact.php
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'subject') ?>
<?= $form->field($model, 'body')->textArea(['rows' => 6]) ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
</div>
<?php ActiveForm::end(); ?>
請添加代碼和更多細節。 – arogachev
如果模型沒有通過驗證(這意味着它沒有保存),如何查看數據庫中的空白值?使用'load'來進行大規模的分配,而不是像那樣的手動處理。 – arogachev