<?php echo CHtml::checkBoxList('checkbox_list_name', '', array(
'Users' => 'All Users',
'Claim' => 'Claim Request',
'Business' => 'Add Business'
), array('id'=>'checkbox-list-id','class'=>'checkboxlist', 'required')). "<br>"; ?>
我已经编写了以下代码来制作一个复选框,我想把它变成一个像Html中那样的必填字段。
答案 0 :(得分:0)
您好您可以添加javascript
function
以阻止表单提交,但如果禁用了javascript则会失败,因此您应同时使用javascript
和server side validation
。
**Server Side validation**
1)在variable
(虚拟变量)
model
Model.php
class Model extends CActiveRecord
{
/**
* @return string the associated database table name
*/
public $checkbox_list_name;
2)在模型中的安全规则中定义
public function rules()
{
array('checkbox_list_name','safe'),
}
3)在你的form.php中
<?php echo $form->checkBoxList($model,'checkbox_list_name', array(
'Users' => 'All Users',
'Claim' => 'Claim Request',
'Business' => 'Add Business'
), array('id'=>'checkbox-list-id','class'=>'checkboxlist', 'required')). "<br>"; ?>
<?php echo $form->error($model,'checkbox_list_name'); ?>
4)在YourController.php中
检查是否选中了复选框
public function actionYouraction() {
$model = new Model();
$this->performAjaxValidation($model);
if (isset($_POST['Model'])) {
if($_POST['Model']['checkbox_list_name'] == ''){
$model->addError('checkbox_list_name', 'Select At least one!!!'); // this will through error if checkbox is not selected
}else{
$model->attributes = $_POST['Model'];
$model->save();
}
$this->render('view', array(
'model' => $model,
));
}
Javascript方法 - 这会计算文本框的长度,如果没有选择至少一个
,则返回false<script type="text/javascript">
$('#user-form').submit(function() {// relace user-form id with your CActiveRecord form id
if(!($('input[type="checkbox"]:checked').length)) {
alert("Select at least one!!!");
return false;
}
return true;
});
</script>