我有一个表单,在用户提交表单和验证正常后,我想在模式窗口中要求他的电子邮件和昵称。如果用户填写并提交电子邮件和昵称,我想验证它,并将其保存为新记录或获取现有记录的id (以防电子邮件已经在过去使用)。如果验证不成功,用户应该能够在相同的模式下更正值。如果一切正常,我想保存表单,包括创建用户id。
我已经完成了表单保存和用户创建/查找过程。我只是不知道,如何把这些放在一起,在我上面描述的场景中工作。有没有人能解释一下,在Yii中应该怎么做?我使用的是Yii 1.1.15和Yii Booster。谢谢。
发布于 2014-12-08 12:14:05
在Yii中,默认情况下在update.php和create.php视图中都使用_form.php视图文件。
因此,您可能需要执行smth。相似:在update.php和create.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'),https://stackoverflow.com/questions/27347449
复制相似问题