我在模态对话框上创建了一个表单以插入数据库
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Crear nueva clase</h4>
</div>
<div class="modal-body">
<?php echo validation_errors(); ?>
<?php echo form_open('clase/create');?>
<form class="form col-md-12 center-block">
<div class="form-group">
<input type="text" class="form-control input-lg" id="name" name="name" placeholder="Nombre"/>
</div>
<div class="form-group">
<input type="text" class="form-control input-lg" id="info" name="info" placeholder="Información"/>
</div>
<div class="form-group">
<button typ="submit"class="btn btn-success btn-lg btn-block">Crear</button>
</div>
</form>
</div>
</div>
</div>
</div>
可以正常工作,但未通过验证时的错误消息不会显示在
中<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Clase extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('clase_model','',TRUE);
$this->load->helper(array('form'));
}
function index()
{
if($this->session->userdata('logged_in')){
$data['title'] = 'Gestión de Clases';
$data['clases'] = $this->clase_model->getAll();
$this->load->view('header', $data);
$this->load->view('clase_view', $data);
}
else{
redirect('login', 'refresh');
}
}
function create(){
if($this->session->userdata('logged_in')){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Nombre', 'trim|min_length[2]|required');
$this->form_validation->set_rules('info', 'Información', 'trim');
if($this->form_validation->run() == FALSE){
$data['clases'] = $this->clase_model->getAll();
$this->load->view('header', $data);
$this->load->view('clase_view', $data);
}
else{
if($this->input->post('info')){
$this->insert2($this->input->post('name'),$this->input->post('info'));
}
else{
$this->insert1($this->input->post('name'));
}
}
}
else{
redirect('login', 'refresh');
}
}
function insert2($name,$information){
$dat = array(
'nombre'=>$name,
'info'=>$information
);
$this-> db ->insert('clase',$dat);
echo $name;
redirect('clase', 'refresh');
}
function insert1($name){
$dat = array(
'nombre'=>$name,
);
$this-> db ->insert('clase',$dat);
redirect('clase', 'refresh');
}
}
?>
创建方法在任何情况下都是正确的,但是我需要查看valifdation错误消息,我该怎么办?
答案 0 :(得分:1)
如果要在模态上显示错误消息,则应通过ajax提交表单。从控制器函数使用json_encode函数回显错误消息。如此 -
if ($this->form_validation->run() === FALSE) {
$data = array('error_message' => form_error('input_name'));
echo json_encode($data);
}
使用jQuery执行此操作 -
$(document).on("click", ".btn", function () {
$.ajax({
type: "POST",
url: "your/url",
data: {your:data},
success: function(data) {
//and from data parse your json data and show error message in the modal
var obj = $.parseJSON(data);
if(obj!=null)
{
$('#err_mssg').html(obj['error_message']);
}
}});
});