【发布时间】:2014-07-08 10:22:04
【问题描述】:
我的 yii 项目有问题。在我的管理面板中,我有一个使用CActiveForm 小部件创建商店产品的表单。像这样的:
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'product-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
));
echo $form->errorSummary($model);
?>
<div class="row-fluid input-block-level-container">
<div class="span12">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'name'); ?>
<?php if('help.name' != $help = Yii::t('crud', 'help.name')) {
echo "<span class='help-block'>{$help}</span>";
} ?>
</div>
</div>
... more fields in the same manner ...
<?php $this->endWidget() ?>
我的验证规则是:
public function rules()
{
return array_merge(
parent::rules(), array(
array('name, category_id, vendor_id', 'required'),
array('description', 'safe'),
array('category_id, vendor_id', 'numerical', 'integerOnly'=>true),
array('name', 'length', 'max'=>255),
array('id, name, category_id, vendor_id', 'safe', 'on'=>'search'),
)
);
}
在我的控制器中,我有这一行:
$model->attributes = $_POST['Product'];
应该用来自$_POST['Product']的值填充模型属性
但是在提交表单后,我收到一个错误,即必填字段为空,尽管它们实际上不是。 如果在我的控制器中我放了这样的东西:
$model->name = $_POST['Product']['name'];
$model->category_id = $_POST['Product']['category_id'];
$model->vendor_id = $_POST['Product']['vendor_id'];
表格已正确处理。但是ajax验证仍然说表单无效。 感谢任何帮助!
编辑: 动作代码:
public function actionCreate()
{
$model = new Product;
$model->scenario = $this->scenario;
$this->performAjaxValidation($model, 'product-form');
if(isset($_POST['Product'])) {
$model->attributes = $_POST['Product'];
if(isset($_POST['Product']['Attribute']))
$model->setRelationRecords('attributes', $_POST['Product']['Attribute']);
try {
if($model->save()) {
if (isset($_GET['returnUrl'])) {
$this->redirect($_GET['returnUrl']);
} else {
$this->redirect(array('view','id'=>$model->id));
}
}
} catch (Exception $e) {
$model->addError('id', $e->getMessage());
}
} elseif(isset($_GET['Product'])) {
$model->attributes = $_GET['Product'];
}
$this->render('create',array( 'model'=>$model));
}
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='product-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
【问题讨论】:
-
你能显示整个动作代码吗?
-
请
Controller::performAjaxValidation()! -
添加了 performAjaxValidation 方法。实际上它的代码是 gii 的典型代码
-
为什么要合并规则?父模型类有哪些规则?
-
父类是 CActiveRecord。
rules()的代码由gii生成。我收起parent::rules()但没有效果
标签: forms validation activerecord yii