Timothy Fisher
Timothy Fisher

Reputation: 1129

How to return data from a form validation callback method in CodeIgniter?

In the CodeIgniter docs here

The note at the bottom of that section states:

You can also process the form data that is passed to your callback and return it. If your callback returns anything other than a boolean TRUE/FALSE it is assumed that the data is your newly processed form data.

I have a callback function that validates an image upload and does the upload, like this:

public function upload() {
    $this->form_validation->set_rules('imageFile', 'Image', 'callback_validate_image');
    // ...
}

And then the callback function:

public function validate_image() {

        if (empty($_FILES['imageFile'])) {
            $this->form_validation->set_message('validate_image', 'Please select a file');
            return false;
        }

        $config = array (
            'upload_path' => './uploads/',
            'allowed_types' => 'jpg|jpeg|png|gif',
            'max_size' => '5048576'
        );

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('imageFile')) {
            $this->form_validation->set_message('validate_image', $this->upload->display_errors());
            return false;
        } else {
            $data = array('upload_data' => $this->upload->data());
            return $data;
        }

}

How can I return the $data to the upload function so that I can insert all data into the database in one query?

Upvotes: 1

Views: 1036

Answers (1)

Abdulla Nilam
Abdulla Nilam

Reputation: 38584

If i did your code part, i'll do like this

function upload() 
{

    // 'required' doesn't work on file inputs so use empty()
    if (empty($_FILES['imageFile'])) {
        // show error message
    }

    if ($this->form_validation->run() == FALSE)
    {
            echo "Please select a file";
            //$this->load->view('myform');
    }
    else
    {
        $config = array (
            'upload_path' => './uploads/',
            'allowed_types' => 'jpg|jpeg|png|gif',
            'max_size' => '5048576'
        );

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('imageFile')) 
        {
            $this->form_validation->set_message('validate_image', $this->upload->display_errors());
            return false;
        } 
        else {
            $data['upload_data'] = $this->upload->data();
            $data['form_data'] = $this->input->post(NULL, TRUE);
            var_dump($data);
        }
    }
}

Didn't went through the upload part. Test it before run it

Upvotes: 1

Related Questions