Problem with validation_errors - El Forum - 04-15-2009
[eluser]Unknown[/eluser]
Hi everyone!
I am new at CI and total noob, so this question maybe is stupid, but I don't get it. I created simple app for adding comments to news. Problem is, when somebody submit empty fields, error messages don't show. I used "echo validation_errors();". Can you help me to get this work?
Code: <?php // SHOW FORM FOR COMMENTS // ?>
<div><?php echo validation_errors(); ?></div>
<?php echo form_open('news/comment_insert'); ?>
<div><?php echo form_hidden('news_id', $this->uri->segment(3)); ?></div>
<div><?php echo form_input(array('name' => 'author', 'type' => 'text', 'class' => 'font')); ?></div>
<div><?php echo form_textarea(array('name' => 'body', 'rows' => '10', 'cols' => '50', 'class' => 'font')); ?></div>
<div><?php echo form_input(array('value' => 'Submit Comment', 'type' => 'submit', 'class' => 'font')); ?></div>
<?php echo form_close(); ?>
Code: function comment_insert()
{
// Set rules
$this->form_validation->set_rules('author', 'author', 'required');
$this->form_validation->set_rules('body', 'body', 'required');
if ($this->form_validation->run() == FALSE) {
// Redirect
redirect('news/comments/' . $_POST['news_id']);
} else {
// Insert comment in database
$this->db->insert('comments', $_POST);
// Redirect
redirect('news/comments/' . $_POST['news_id']);
}
}
Problem with validation_errors - El Forum - 04-15-2009
[eluser]NogDog[/eluser]
I think the redirect is the problem. Instead of redirecting, just load the view with the form.
Code: if($this->form_validation->run() == false) {
$this->load->view('view_name_goes_here']);
}
Problem with validation_errors - El Forum - 04-15-2009
[eluser]Unknown[/eluser]
Yeah that was the problem. But I needed to load news and comments again in this case. I don't know if this is best solution, but at least it's working now.
Code: function comment_insert()
{
// Set rules
$this->form_validation->set_rules('author', 'author', 'required');
$this->form_validation->set_rules('body', 'body', 'required');
if ($this->form_validation->run() == FALSE) {
// Load header
$data['title'] = "-> News -> Comments";
$this->load->view('templates/elsi/header_view', $data);
// Load news
$this->db->where('id', $this->uri->segment(3));
$data['news'] = $this->db->get('news');
// Load comments
$this->db->where('news_id', $this->uri->segment(3));
$data['comments'] = $this->db->get('comments');
$this->load->view('templates/elsi/comment_view', $data);
// Load footer
$this->load->view('templates/elsi/footer_view');
} else {
// Insert comment in database
$this->db->insert('comments', $_POST);
// Redirect
redirect('news/comments/' . $_POST['news_id']);
}
}
|