在我的CakePHP项目中,我想显示错误消息,但是不起作用。
提交时,我希望它显示一条错误消息,例如:“此字段为必填项”,但是默认情况下它显示为“请填写此字段”。我更改了消息,但从内核开始并没有改变。
我的 View ,模型和 Controller 代码如下:add_district.ctp
:
<div class="pg_title txtLeft">Add District</div>
<?php echo $this->Form->create('Admins', array('action' => 'add_district'));?>
<table>
<tbody>
<tr>
<td><label>District Name<span class="red required">*</span></label></td>
<td><?php echo $this->Form->input('District.district_name',array('label'=>false,'div'=>false,'size'=>50,'style'=>'width:330px;')); ?></td>
</tr>
<tr>
<td colspan="2" align="right" style="padding-right: 113px;"><input type="reset" value="Reset"> | <?php echo $this->Form->submit('ADD', array('div' => false));?></td>
</tr>
</tbody>
</table>
<?php print $this->Form->end();?>
<div class="clear"></div>
型号:
District.php
<?php
App::uses('AppModel', 'Model');
/**
* Admin Login Model
*
*/
class District extends AppModel
{
public $name='District';
public $usetables='districts';
public $validate = array(
'district_name' => array(
'rule' => 'notEmpty',
'allowEmpty' => false,
'message' => 'This field is required'));
}
?>
我的 Controller 代码是(
AdminController.php
):public function add_district()
{
$this->layout='common';
$this->District->create();
$this->District->set($this->data);
if(empty($this->data) == false)
{
if($this->District->save($this->data))
{
$this->Session->setFlash('District Added Successfully.');
$this->redirect('add_district');
}
}
else
{
$this->set('errors', $this->District->invalidFields());
}
}
最佳答案
该消息“请填写此字段”是来自浏览器本身,而不是来自CakePHP。
因此,Firefox和Chrome(可能还有其他浏览器?)会自动检查标记为必填的字段,然后在提交表单时,甚至在将该表单数据发送到服务器之前,如果未填写必填字段,浏览器将显示您该默认 pop 消息:“请填写此字段”。
这是浏览器的默认行为,与您的代码无关。如果您想检查Cake错误消息是否正常,请尝试使用Safari(从6.0.2版开始,该功能似乎没有“自动检测必填字段”功能)。在Safari中,您应该返回自己的CakePHP错误消息。
您还可以通过将表单本身的autovalidate属性传递为false来防止在浏览器中进行错误检查-请参见Disable validation of HTML5 form elements
关于error-handling - 无法更改CakePHP 2.3中的默认错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14685945/