Question

I'm building a pretty complex and dynamic form via the Lithium PHP framework.

I've got the form working and saving to MongoDB with little problem. But I am having trouble with validation.

Simple validations (such as checking if a field is not empty or is numeric) are working fine. But I have to do a few complex validations that rely on a number of fields in the form.

For example, I have a form where a user can enter a question and then enter an unlimited number of possible answers for this question. The field ID for each answer is listed such as "answer_1", "answer_2", "answer_3", etc. The user can add an unlimited number of answers. This happens via some fancy JavaScript that inserts extra elements to the form on the client side.

At the validation level, I want to make sure that every answer which was added is not null.

I would like to do this using the "traditional" Validator functionality built within Lithium. I am also doing this at the Model level, not the Controller level (note - I have a workaround to solve this on the Controller level, but would rather do it the "right" way at the Model)

The problem, as far as I can tell, is that you can only pass a single value to the validator rule. I just need to pass back ALL values in the form to the validator. If I could do that, I would be golden. The pseudo-code for what I'm looking to do looks like this:

        Validator::add('CorrectTest', function(&$value, $format = null, array $options = array()) {

        foreach ($_data as $key => $value) {
            if (stristr($key, "answer_")) {
                if ($value == "") {
                    return false;           
                }
            }
        }   

        return true;
    });

This code doesn't work, because the $_data value is not present. If I could just figure out a way to get a fully-populated "$_data" object into the Validator function, I think I could get this to work.

Thanks in advance for the help

Was it helpful?

Solution

Take a look at what's inside $options. You should have a 'values' key in there that has all of the values from the form.

So try $_data = $options['values'];

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top