我已经使用 Yii2 完成了 Web 应用程序,以这种形式提交的值没有保存在数据库中。我只是使用了模型+控制器+视图结构。实际上表单正在Mysql数据库中提交,但是当我访问数据库时,我只能看到所有条目的空白值
站点控制器.php
<?php
namespace appcontrollers;
use Yii;
use yiifiltersAccessControl;
use yiiwebController;
use yiifiltersVerbFilter;
use appmodelsLoginForm;
use appmodelsContactForm;
use appmodelsCanForm;
use appmodelsUploadForm;
use yiiwebUploadedFile;
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 appmodels;
use Yii;
use yiibaseModel;
use yiidbActiveRecord;
/**
* ContactForm is the model behind the contact form.
*/
class ContactForm extends yiidbActiveRecord
{
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(); ?>
从您给出的代码来看,您似乎尚未将模型与数据库绑定。
将此函数添加到模型中:
public static function tableName()
{
return 'your_table_name';
}
此外,您不必手动将每个值分配给模型。海量任务为你做到这一点。