Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Model validation outside of forms
  • Hi. I am facing a very annoying problem. I am writing an API to which users can post data. Upon receiving data, I try to save the objects to their appropriate model. Of course, the supplied objects can be invalid, so I have a try-catch statement around the save method, that throws an exception.

    All of this works. But I really can't seem to find a way to get the actual validation errors out, so I can send them back in a proper way to the user. All I can output, it the Orm\ValidationFailed exception, which contains a bunch of formatted html with the errors inside. I need the errors without the html, just the raw error data.

    Has anyone already succeeded at doing this? This is my code:

  • The fieldset is passed back in the exception. You can access it on the exception object using the get_fieldset() method. Using the fieldset, you can access the corresponding validation object, which in turn gives you access to the errors.

    public function add_lead(Model_Lead $lead)
    {
        try
        {
            $lead->save();
        }
        catch(Orm\ValidationFailed $e)
        {
            // returns the individual ValidationError objects
            $errors = $e->get_fieldset()->validation()->error();
        }
    }

    On a ValidationError object you can access the properties "field", "value", "rule", "params" with info on what exactly failed, and get_message(), which will return the corresponding error message.
  • That is what I tried in my code snippet, but the $e->get_fieldset()->validation() returns NULL :(
  • And what does $e->get_fieldset() return?

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion