我在 CakePHP 中的表单有一个奇怪的问题。我有一系列以复选框开头的问题。如果选中该复选框,我希望另外两个输入字段是必需的。否则,如果未选中,它们是可选的。我编写了一个自定义函数来验证输入字段。这是其中之一:
public function rn_number () {
if ($this->data['Education']['rn_box'] == 1) {
if($this->data['Education']['rn_number'] == '')
return false
}
return true;
}
public $validate = array(
'rn_number' => array(
'rn_number'=>array(
'rule' => 'rn_number'
),
),
);
验证工作正常。对于上述规则,它检查 id 为 'cna_box' 的复选框的值是否为 1,或者被选中,然后检查 id 为 'cna_number' 的输入是否为空。如果是,则返回 false。如果选中该复选框,则始终要求提交数据。我的问题是,当“cna_number”等必需的输入字段为空白时,它有时才表明存在错误。在第一次提交时,它将始终指示这些字段是必需的。但是,如果您再次提交表单,它不会表明这些字段是必填的,也不会显示错误消息——这会让用户感到困惑。
我注意到复选框有一个隐藏的输入。提交复选框并返回有错误的页面后,隐藏输入的值为 0,复选框的值为 1。您认为这与问题有关吗?
更新:
这是我认为生成相关表单字段的代码:
echo $this->Form->inputs(array(
'legend'=>'Certifications',
'rn_box'=>array(
'type'=>'checkbox',
'label'=>'RN',
),
'rn_number'=>array(
'label'=>'RN Number:',
'value' => $results['Education']['rn_number']
),
'rn_exp_date' => array(
'label' => 'Expiration Date:',
'dateFormat' => 'MDY',
'monthNames' => FALSE,
'minYear' => date('Y'),
'maxYear' => date('Y') + 20,
'empty' => TRUE,
'after' => '<span class="small">(MM/DD/YYYY)</span>',
'class' => 'input-mini',
'selected'=>strtotime($results['Education']['rn_exp_date'])
),
));
和控制器代码:
public function pagethree() {
/**
** If user has completed this form,
** grab data for editing
**/
$this->set('results', $this->Education->find('first', array(
'conditions' => array('Education.user_id' => $this->Auth->user('id'))
)));
if ($this->request->is('post')){
$this->request->data['User']['id'] = $this->Auth->user('id');
/**
** Find if there is any data
** in this user in the Basics
** table.
**/
$existingRecordId = $this->Education->find('first', array(
'conditions' => array('Education.user_id' => $this->Auth->user('id')),
'fields' => array('Education.id')
));
/**
** If data exists, return row
** id (PK). Set this value to
** id key, so saveAll() updates
** existing row.
**/
if(sizeof($existingRecordId)>0)
$this->request->data['Education']['id'] = $existingRecordId['Education']['id'];
if ($this->User->saveAll($this->request->data)) {
$this->redirect(array('action'=>'pagefour'));
} else {
$this->Session->setFlash('Your data have not been saved');
}
}
}