codeigniter form_validation is not working...(for me)
Ok, I'm trying to validate a form in codeigniter
as a first step I want to make all fields in my form required to make an entry... but I can't make it work
here is the code:
myBlog.php
<?php
class MyBlog extends Controller{
function MyBlog(){
parent::Controller();
$this->load->helper('url'); //here we load a url class that we use later
$this->load->helper('form');// here we load form class
$this->load->scaffolding('entries'); //scaffolfing is a feature that lets you add or remove elements from the database
$this->load->library('form_validation');//load validation class used to validate our forms...
}
function index(){
$data['title'] = "My Blog Title"; //the title of my blog
$data['query'] = $this->db->get('entries'); //here we make a small query to entries table
$this->load->view('myBlog_view', $data); ///load all data variables on myBlog_view.php
//this is also for the form validation
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('body', 'Body', 'required');
$this->form_validation->set_rules('author', 'Author', 'required');
if ($this->form_validation->run() == FALSE)
{
//$this->load->view('myBlog_view');
}
else
{
$this->load->view('formSuccess_view');
}
}
function myBlog_insert(){
$this->db->insert('entries', $_POST);
redirect('myBlog/');
}
}
?>
also myBlog_view.php file:
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<?php foreach($query->result() as $row): ?>
<div class='curvebox'>
<h3><?=$row->title?></h3>
<p class="bodyText"><?=$row->body?></p>
<div class="author"><?="by: ".$row->author." on ".date("D d M Y开发者_JAVA技巧 h:i:s A", strtotime($row->date_time))?></div>
<p class="comments"><?=anchor('myBlog/comments/'.$row->id, 'Comments');?></p>
</div>
<?php endforeach; ?>
<div class="theForm">
<?php echo $this->form_validation->error_string; ?>
<?=form_open('myBlog/myBlog_insert');?>
<label for="title">Title:</label>
<input type='text' name="title" size="40" id="title" />
<p>
<label for="body">Body:</label>
<textarea name="body" rows = "10" cols="60" id="body"></textarea>
</p>
<p>
<label for="author">Author:</label>
<input type="text" name="author" size="40" id="author"/>
</p>
<p><input type="submit" value="Submit New Post"/></p>
</form>
</div>
</body>
</html>
everything works fine except the fact that it would accept entries with by a form half-filled
sorry for the long code.... any help would be appreciated
You want to have your form post to itself. Right now it's skipping the validation.
All of your validation functions are in the index method. Change this line in myBlog_view.php:
<?=form_open('myBlog/myBlog_insert');?>
to:
<?=form_open('myBlog');?>
And then you'll need to call the insert method after the validation, so in your controller, before this line: $this->load->view('formSuccess_view');
you'll need to add in this:
$this->myBlog_insert();
See if that works.
精彩评论