Welcome Guest, Not a member yet? Register   Sign In
Form Validation Error Messages Not Showing
#1

[eluser]M3Shark[/eluser]
Hi everyone, I am having some trouble with the results from form validation not showing up. I am creating a comment area for a blog. The actual form validation is working (making sure that the user enters something for author and comment field), however, the error messages are not showing up if it fails and reloads the page. Anyway, here is my code:
Blog Controller:
Code:
function comment_insert() {
        $this->load->library('form_validation');
        
        // field name, error message, validation rules
        $this->form_validation->set_rules('author', 'author', 'trim|required');
        $this->form_validation->set_rules('comment', 'comment', 'trim|required');
        
        if($this->form_validation->run() == FALSE)
        {
            redirect('blog/show_post/'.$_POST['entry_id']);
        }
        else
        {
        $this->load->model('blog_model');
        date_default_timezone_set('America/Los_Angeles');
        $data = array(
            'author' => $this->input->post('author'),
            'comment' => $this->input->post('comment'),
            'entry_id' => $this->input->post('entry_id'),
            'date' => date('Y-m-d-g-i-s'),
        );
        
        $this->blog_model->add_comment($data);
        redirect('blog/show_post/'.$_POST['entry_id']);
        
        }
    }
    function show_post() {
        $this->load->model('blog_model');
        $data = array();
        if($query = $this->blog_model->get_post())
        {
            $data['records'] = $query;
        }
        if($query = $this->blog_model->get_comment())
        {
            $data['comments'] = $query;
        }
        $data['main_content'] = ('post_view');
        $this->load->view('includes/template', $data);
    }

And the comment form in the post view:
Code:
<div id="comment_form"><div id="leave_comment"><h3>Leave a Comment</h3></div>
    &lt;?php
    echo form_open('blog/comment_insert');
    echo form_hidden('entry_id', $this->uri->segment(3)); ?&gt;
    <div id="form_name"><p>NAME:<br/>&lt;?php echo form_input('author'); ?&gt;</p></div>
    <div id="text_box">&lt;?php
    $data = array(
              'name' => 'comment',
              'rows' => '10',
              'cols' => '50',
            );
    ?&gt;
    <p>COMMENT:<br/>&lt;?php echo form_textarea($data); ?&gt;</p></div>
    <div id="submit">&lt;?php echo form_submit('submit', 'Submit Comment'); ?&gt;
    </div>
    &lt;?php echo form_close(); ?&gt;
    &lt;?php echo validation_errors(); ?&gt;
    </div>

Thank you for your help.
#2

[eluser]WanWizard[/eluser]
That is because you redirect, which is a new page request, that is not aware of the previous request, and it's state.

Either don't do the redirect but reload the view (which will also allows you to repopulate the form with the posted values, so the user doesn't have to type it all in again), or store the result of validation_errors() in the session, retrieve it after the redirect, and pass it to the view.
#3

[eluser]M3Shark[/eluser]
I am sure this is a really stupid/easy question, but how do I go about reloading the view while not loosing track of which post I am looking at? aka the 'entry_id'.
#4

[eluser]WanWizard[/eluser]
You make it a bit complicated by spliting the different functions.

In pseudo code, this is what I usually do:
Code:
if ( new_record )
{
    $data['record'] = array(); // initial values
}
else
{
    $data['record'] = $this->model->get_record(); // returns an array
}

if ( form_was_submitted )
{
    $this->form_validation_set_rules(); // add your rules

    $validated = $this->form_validation->run(); // run the validation

    // update the loaded record with the values from the form using set_value()
    $data['record']['field'] = set_value('field'); // for every form field

    if ( $validated  == TRUE )
    {
        // save the record, or insert it if it was a new one

        // no errors. you could also store a success message here
        $data['errors'] = array();
    }
    else
    {
        // get the validation errors
        $data['errors'] = validation_errors();
    }
}

// display the form
$this->load->view('form', $data);
#5

[eluser]M3Shark[/eluser]
WanWizard:
Thank you so much for your help. I really appreciate you taking the time to respond and try to help me.

Unfortunitly, I am still not following you. I can't figure out how to make my code into what you suggested to do. But I really do want to learn/figure it out. Any chance you are willing to go into a little more detail and help me figure out what to do?

Thank you.
#6

[eluser]WanWizard[/eluser]
This flow has to go in a controller method. The idea is that everything is handled within that same method, to the form action should be that method as well.
From what I understand from your code, you only have an insert option, not an edit option, that makes it a bit easier.

Code:
class Post extends Controller
{
    function Post
    {
        parent::Controller();
    }

    function show()
    {
        // initialize the data array
        $data = array('validation' => TRUE);

        // load the post data for the view. I assume it returns an array or FALSE

        $this->load->model('blog_model');
        if( ! $data['records'] = $this->blog_model->get_post() )
        {
            $data['records'] = array();
        }
        $data['main_content'] = ('post_view');

        // was the comment form submitted?

        if( $this->input->post('submit') )
        {
            // load the form validation library
            $this->load->library('form_validation');
        
            // field name, error message, validation rules
            $this->form_validation->set_rules('author', 'author', 'trim|required');
            $this->form_validation->set_rules('comment', 'comment', 'trim|required');

            // run the validation
            $validated = $this->form_validation->run();
            
            // create the comment array
            date_default_timezone_set('America/Los_Angeles');
            $data['comment'] = array(
                'author' => set_value('author'),
                'comment' => set_value('comment'),
                'entry_id' => set_value('entry_id'),
                'date' => date('Y-m-d-g-i-s'),
            );

            // did the form validate?
            if ( $validated === FALSE)
            {
                // no, fetch the error messages
                $data['messages'] = validation_errors();
            }
            else
            {
                // yes, save the comment
                $this->blog_model->add_comment($data['comment']);
                $data['messages'] = "Blog commit is succesfully added";
            }

            // we need the validate result in the form
            $data['validated'] = $validated;
        }

        // load the comment data for the view. I assume it returns an array or FALSE
        // this will include the one just added if the form validated
        if( ! $data['comments'] = $this->blog_model->get_comment() )
        {
            $data['comments'] = array();
        }

        $this->load->view('includes/template', $data);
    }
}

Now, in your form, you can display the post, and all the comments. $data['messages'] contains any messages you need to display. If $data['validation'] is TRUE, you display an empty comment form at the bottom. If it is false, you populate the form fields from $data['comment'], so the user doesn't have to re-enter the information that he already put in the form.

In your view, the form action should then be pointed to 'blog/show' so a post of the form will return to this same method.
#7

[eluser]M3Shark[/eluser]
Thank you so much, I have gotten it working now. I really appreciate you helping me. Thank you.
#8

[eluser]phpgeek[/eluser]
[quote author="WanWizard" date="1282019775"]That is because you redirect, which is a new page request, that is not aware of the previous request, and it's state.

Either don't do the redirect but reload the view (which will also allows you to repopulate the form with the posted values, so the user doesn't have to type it all in again), or store the result of validation_errors() in the session, retrieve it after the redirect, and pass it to the view.[/quote]

Hello there,
I have the same problem, is there any way to show form errors without having to redirect or having to load views again? The problem is that i have several views: header, body, sidebar, form and footer (I use separate HTML code to make them work toghther) and i load them using an index function from my Controller like this:

Code:
/*Prepago Controller*/
class Prepago extends Controller {

    function Prepago()
    {
        parent::Controller();
        $this->load->model('PrepagoModel');    
    }
    
    function index()
    {
function index()
    {
        //Conseguir los planes        
        $comboPlanes= $this->getPlanes();
        
        //Elementos de página
        $data = array(
               'title' => 'Clientes por plan prepago',
                'Fecha' => $this->setFormPrepago(),
                'comboPlanes' => $comboPlanes,
                'comboStatus' => $this->setFormPrepago(),
                'comboModelo' => $this->getModeloEquipo()
          );
        
        $this->load->view('header', $data);
        $this->load->view('prepago/instrucciones');
        $this->load->view('welcome_message', $data);
        $this->load->view('prepago/form_pre_plan', $data);
        $this->load->view('footer');

    }
here is my view
Code:
/*form_pre_plan View*/
&lt;?php
echo validation_errors();  //This doesn't do anything

echo form_open('validation', array('name'=>'myform'));                                          
//Some form elements here....... ?&gt;
<table>
<tr>
    <td>Tipo de Cliente</td>
    <td>&lt;?php echo "Natural ".form_radio('radioTipoCliente',array('value'=>'Natural','checked'=>'checked')).'</br>'."Jur&iacute;dico ".form_radio('radioTipoCliente',array('value'=>'Natural')); echo form_error('radioTipoCliente'); ?&gt;</td>
</tr>
</table>
&lt;?php echo form_close(); ?&gt;

And the validation Controller
Code:
&lt;?php
class Validation extends Controller {

    function Validation()
    {
        parent::Controller();            
    }
    function index()
    {                        
        $this->load->library('form_validation');
        $config = array(
               array(
                     'field'   => 'radioTipoCliente',
                     'label'   => 'Tipo de Cliente',
                     'rules'   => 'required'
                  )
            );
        $this->form_validation->set_message('required', 'My message');    
        $this->form_validation->set_rules($config);
                
        if ($this->form_validation->run() == FALSE){
            //I load the whole form using a call to this controller with index method
            redirect('prepago/');            
        }
        else{
            //Something here if everything is alright
        }
        
    }    
}    
?&gt;

And then, when there is an error i couldn't see the message in the validated page after i submit the form. Therefore my question is, how can i show the whole validated page without having to call every single view again. As you see it didn't work with redirect method. Thanks in advance.




Theme © iAndrew 2016 - Forum software by © MyBB