Welcome Guest, Not a member yet? Register   Sign In
trying to understand form_validation
#1

[eluser]rabidmacine9[/eluser]
hello everybody I'm trying to make all fields in a form required but I haven't really understand how form_validation works...
so at this point the form doesn't do anything it doesn't post any comments and it doesn't display any errors even when all fields are filed
this is the code of the controller:

Code:
<?php

class MyBlog extends Controller{
        
        
   function MyBlog(){
       parent::Controller();
       $this->load->helper(array('url','form','html')); //here we load some classes that we use
      
       $this->load->scaffolding('entries');  //scaffolfing is a feature that lets you add or remove elements from the database
        $this->load->scaffolding('comments');
        
       $this->load->library('form_validation');//load validation class used to validate our forms...
   }
  
  
      
function comments(){
    
      $data['title'] = "My comment Title"; //the tille on the comments page
      $data['heading'] = "My comment Heading"; //the header on the comments page
      $entry_id = $data ['entry_id'] = $this->uri->segment(3); //here we grub the id of the entry we comment
      $this->db->where('entry_id', $this->uri->segment(3));  //here we assign the number of the entry to an entry_id number in the comments table
      $data['query'] = $this->db->get('comments'); //this is a query for comments
      $data['relevantEntryQuery'] = $this->db->query("SELECT * FROM entries WHERE id = $entry_id");  //and this query comes up with the relevant to the comments entry
      
      $this->load->view('comment_view', $data); //loads all data variables to comment_view.php
      
        //here is the validation of the form, all fields required!
        $this->form_validation->set_rules('body', 'Body', 'required');
        $this->form_validation->set_rules('author', 'Author', 'required');
    
        
        
        
      
      if ($this->form_validation->run() == TRUE)
        {    
        
           $this->db->insert('comments', $_POST);
      
           redirect('myBlog/comments/'.$entry_id);
          // $this->comment_insert();
            $this->load->view('myBlog/comments/'.$entry_id);
        }
    
    
    }
      
function comment_insert(){
      
       $this->db->insert('comments', $_POST);
      
       redirect('myBlog/comments/'.$_POST['entry_id']);
       }
      
              


      
      
}

?>

and here is the comment_view.php file with the form...
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
&lt;html &gt;
&lt;head&gt;
&lt;title&gt;&lt;?php echo $title; ?&gt;&lt;/title&gt;

&lt;/head&gt;
&lt;body&gt;



&lt;?php $relevantEntry = $relevantEntryQuery->row_array();?&gt;

<div class='curvebox'>
<h1><div class="title">&lt;?php echo $relevantEntry['title']; ?&gt;</div></h1>
<p><div class="bodyText">  &lt;?php echo $relevantEntry['body']; ?&gt;</div></p>
<p><div class="author">&lt;?php echo $relevantEntry['author']." | ".date("D d M Y h:i:s A", strtotime($relevantEntry['date_time'])); ?&gt;</div></p>
</div>




&lt;?php if($query->num_rows() > 0): ?&gt;
     &lt;?php foreach($query->result() as $row): ?&gt;


<div class='commentBox'>
     <div class="commentauthor">&lt;?php echo $row->author." | ".date("D d M Y h:i:s A", strtotime($row->date_time));?&gt;</div>
    
     <p><div class="commentbody">&lt;?=$row->body?&gt;</div></p>
</div>    

    

    &lt;?php endforeach; ?&gt;
&lt;?php endif; ?&gt;






//this is the place where the form is filed!

&lt;? echo form_hidden('entry_id',$this->uri->segment(3));?&gt;

&lt;?php echo validation_errors(); ?&gt;
&lt;?php echo form_open('myBlog/comments/'.$entry_id);?&gt;
<div class="theForm">
<h3>Post Your Comment Here:</h3>
<p><div class="in">
<label for="body">Comment:</label>
&lt;textarea name="body" rows = "10" cols="60" class="txt"&gt;&lt;/textarea>
</p></div>
<p><div class="in">
<label for="author">Author:</label>
&lt;input type="text" size="30" name="author" class="txt"/&gt;
</p></div>
<p>&lt;input type="submit" value="Submit Comment" class="btn"/&gt;&lt;/p>
</div>
&lt;/form&gt;



<a href="/myBlog/CodeIgniter_1.7.2/index.php/myBlog"  id="linkBack">Back to Blog</a>




&lt;/body&gt;
&lt;/html&gt;

any ideas?
sorry for the size of the question...
#2

[eluser]InsiteFX[/eluser]
Code:
if ($this->form_validation->run() == FALSE)
{
    $this->load->view('myform');
}
else  // form submit below here!
{
    $this->db->insert('comments', $_POST);
      
    redirect('myBlog/comments/'.$entry_id);
    // $this->comment_insert();
    $this->load->view('myBlog/comments/'.$entry_id);
}

InsiteFX
#3

[eluser]rabidmacine9[/eluser]
r u sure?
there is no file named "myForm" in my case and it doesn't seem to change anything in the case the validation is TRUE, even if my question is not so good maybe I could still use some explanation about the form_validation class instead of a straight solution...
thanks anyway.
#4

[eluser]InsiteFX[/eluser]
This is all here in the Users Guide!

Read it, your missing the form set_value part.

[email=http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html]Form Validation[/email]

InsiteFX
#5

[eluser]pickupman[/eluser]
Code:
if ($this->form_validation->run() == FALSE)
{
    $this->load->view('comment_view'); //renders page
}
else  // form submit below here!
{
    $this->db->insert('comments', $_POST);
      
    redirect('myBlog/comments/'.$entry_id);
    // $this->comment_insert();
    $this->load->view('myBlog/comments/'.$entry_id); //renders page
}

Form validation works by creating your validation rules, that will be processed by form
Code:
$this->form_validation->set_rules('field_name', 'field name', 'required');

You then need a block of code that checks whether the validation rules have been satisfied.
Code:
if($this->form_validation->run() == FALSE){
  //The form failed. Try reloading the form here again
}else{
  //The form was successful. May want to add this to the DB or redirect to another page.
}

Another helpful feature of form validation is using the set_value() function. You can repopulate the fields that a user typed, and when the form fails, the values they did fill out will be added back into the fields
Code:
&lt;input name="some_field" type="text" size="10" value="&lt;?php echo set_value('some_field', 'default value');?&gt; " /&gt;
#6

[eluser]rabidmacine9[/eluser]
this is becoming more and more difficult... I'm trying what you suggest and it doesn't seem to work...
there is also another side effect when that runs:

Code:
if ($this->form_validation->run() == FALSE)
{
    $this->load->view('comment_view'); //renders page
}

the content of the page is displayed twice,
thats why I was using this code in my first post:

Code:
if ($this->form_validation->run() == TRUE)
        {    
        
           $this->db->insert('comments', $_POST);
      
           redirect('myBlog/comments/'.$entry_id);
          // $this->comment_insert();
            $this->load->view('myBlog/comments/'.$entry_id);
        }
it saves the trouble of repeating itself...
but the main problem is that it still wont do any addition to the database...it will redisplay the page with no changes
#7

[eluser]pickupman[/eluser]
What's the point of the redirect() and having a load->view() following it. It will never get called. Also, you data may not be inserting if your field names don't match your DB fields. You also need to watch your html structure on your comments_view file. You have elements in the wrong areas possibly causing your problems. You have a hidden form input above the form tag which will do nothing. You had mixed open and closing div's & p's.

Code:
//View
&lt;?php echo validation_errors(); ?&gt;
&lt;?php echo form_open('myBlog/comments/' . $entry_id, array('entry_id' => $this->uri->segment(3)));?&gt;


<div class="theForm">
    <h3>Post Your Comment Here:</h3>
    <div class="in">
        <p>
            <label for="body">Comment:</label>
            &lt;textarea name="body" rows = "10" cols="60" class="txt"&gt;&lt;?php echo set_value('body');?&gt;&lt;/textarea&gt;
        </p>
    </div>
    <div class="in">
        <p>
            <label for="author">Author:</label>
            &lt;input type="text" size="30" name="author" class="txt" value="&lt;?php echo set_value('author');?&gt;" /&gt;
        </p>
    </div>
    <p>
        &lt;input type="submit" value="Submit Comment" class="btn"/&gt;
    </p>
</div>
&lt;/form&gt;

//MyBlog controller
function comments(){
    
      $data['title']   = "My comment Title"; //the tille on the comments page
      $data['heading'] = "My comment Heading"; //the header on the comments page
      $data['entry_id'] = $this->uri->segment(3); //here we grab the id of the entry we comment
      
      $this->db->where('entry_id', $data['entry_id']);  //here we assign the number of the entry to an entry_id number in the comments table
      $data['query'] = $this->db->get('comments'); //this is a query for comments
      $data['relevantEntryQuery'] = $this->db->get_where('entries', array('id' => (int)$data['entry_id']));  //and this query comes up with the relevant to the comments entry
      
      //here is the validation of the form, all fields required!
      $this->form_validation->set_rules('body', 'Body', 'required|trim');
      $this->form_validation->set_rules('author', 'Author', 'required|trim');
      $this->form_validation->set_rules('entry_id', 'entry id', 'required|trim|is_numeric');      
      
      if ($this->form_validation->run() == TRUE)
      {    
            foreach($_POST as $key => $value){
                $this->db->set($key, $value); //make a little safer
            }
            $this->db->insert('comments');
      
           redirect('myBlog/comments/'.$entry_id, 'refresh'); //prevent reload/reinsert        
      }else{
        
        //Form loaded for first time or form failed. Load form
        $this->load->view('comment_view', $data);
      }
    
    }
#8

[eluser]rabidmacine9[/eluser]
Ok the good news is that I found where the exact problem is...

Everytime I submit the form all data are stored in the DB except "entry_id" so thats why the comments are not displayed as they should be...

Actually I don't want my "entry_id" to be marked as required I just want it to be posted from a hidden field every time I submit a form...

anybody knows how can I do that?


And also...@pickupman
your answer was nice and it had some really good points...but when I replace this line :
Code:
$entry_id = $data ['entry_id'] = $this->uri->segment(3);

with these two lines:
Code:
$data ['entry_id'] = $this->uri->segment(3); //here we grub the id of the entry we comment
      
      $this->db->where('entry_id', $data['entry_id']);


I get an error that $entry_id variable is not defined...
any idea why is that?
thanks a lot to everybody
#9

[eluser]WanWizard[/eluser]
You should always validate everything posted, hidden or not. Besides, you're using this field for database interaction, so I assume you want to make sure it is defined and valid.

Having said that, if you don't want a field to be requied, you can set an empty validation rule. That way it will become available to set_value().
#10

[eluser]RickP[/eluser]
When validation succeeds, the documentation shows using $this->load->view('successpage') but what happens if the user decides to refresh that success page? The uri hasn't changed and the post values are still available so the update procedure would happen a second time.

What is the best way to prevent this? Would using redirect() be a good idea?




Theme © iAndrew 2016 - Forum software by © MyBB