>我有一个表单,在用户提交表单并且验证正常后,我想在模态窗口中询问他的电子邮件和昵称。如果用户填写并提交电子邮件和昵称,我想验证它并将其另存为新记录或获取现有记录的 ID(以防过去已经使用过电子邮件)。如果验证不成功,用户应该能够在同一模式中更正值。如果一切正常,我想保存表单,包括创建用户ID。
我已经完成了表单保存和用户创建/查找过程。我只是不知道,如何把它放在一起,在我上面描述的场景中工作。谁能解释一下,这应该如何在 Yii 中完成?我正在使用 Yii 1.1.15 和 Yii Booster。谢谢。
在 Yii 中,_form.php
视图文件默认用于update.php
视图和create.php
视图。
因此,您可能需要执行类似操作:在"更新.php"和"创建.php"视图中插入带有模式的窗体。这些操作和不同的操作,因此您将逻辑分开;这是MVC的基本优势。
public function actionCreate() {
$model = new Users;
if (isset($_POST['Users'])) {
$model->attributes = $_POST['Users'];
if ($model->save()) { // here in the save() method the valadation is included
// ONLY after we validate and successfully saved we go to update action
$this->redirect(array('update', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
最主要的是,当您尝试保存该方法save()
验证会自动发生。因此,如果验证不成功,逻辑将返回到相同的操作(例如创建),并在视图中填充字段,因为模型已经将数据传递到其中:$model->attributes = $_POST['Users']
.
如果验证成功,我们将进一步重定向。不是 ajax 表单提交,即使是随意提交也适合这里。
public function actionUpdate($id) {
$model = $this->loadModel($id);
if (isset($_POST['Users'])) {
$model->attributes = $_POST['Users'];
if ($model->save()) { // after saving EXISTING record we redirect to 'admin' action
$this->redirect(array('admin'));
}
}
$this->render('update', array(
'model' => $model,
));
}
视图中的表单(更新/创建)保持原始设计。
在模型规则()中验证唯一性很简单:
array('username, email', 'unique'),
电子邮件语法的电子邮件评估似乎是这样的:
array('email', 'email'),