1

I am developing an REST API using Codeigniter. I need to have all error messages from Form validation in array format so that I can easily respond in either JSON or XML.

Right now Codeigniter is delivering error messages with <p> as delimiters (see below) but that is not good for a REST based API.

<p>There was an error with this item</p>

How can I get errors in an array?

Thankful for all input!

3
  • Tags. They don't go in titles. Commented Aug 18, 2011 at 15:03
  • Probably the Codeigniter Form module is not flexible enough for your purpose. Is replacing it with a more flexible implementation an option for you? Commented Aug 18, 2011 at 15:28
  • Perhaps. Do you know of any good alternatives? Commented Aug 18, 2011 at 15:40

2 Answers 2

1

The form validation library stores errors in an array and loops through them to generate the error string. They are stored in a private variable called $_error_array. You could extend the library with a simple method that returns the error array.

class MY_Form_validation extends CI_Form_validation
{
    function get_error_array()
    {
        return $this->_error_array;
    }
}

I assume you are familiar with extending core CI libraries, but this extension of the form validation library will give you a method to return the errors as an array with the name attribute's value as the key and the message as the value. I tested it out on one of my projects and it worked fine.

Sign up to request clarification or add additional context in comments.

4 Comments

Interesting! How would such an extension look like?
Cool! How do I use it in my controller?
Never mind. Got it, thank you so much! This is how I access it in my controller: $this->form_validation->get_error_array()
This code works perfectly fine on my local server (Mac) but on the remote server I get a 500 error. What can be wrong?
1

You can transform it easily:

/**
 * @param $errors string
 * @return array
 */
function transformErrorsToArray ($errors) {
    $errors = explode('</p>', $errors);
    foreach ($errors as $index => $error) {
        $error = str_replace('<p>', '', $error);
        $error = trim($error);
        // ... more cleaning up if necessary
        $errors[$index] = $error
    }
    return $errors;
}

2 Comments

Looking good but it adds an empty "slot" in the array at the end of it. How can I leave that out? Array ( [0] => The Number field is required. [1] => )
I like this answer more than the accepted one, as it doesn't require you to change the CodeIgniter core code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.