views:

1299

answers:

3

Hi

I've written a simple callback function which isn't working. My other callbacks (which are in the same library file) work fine so I guess the problem has to do with my code.

The parameter passed in the callback function takes the form of a chunk of PHP which is eval()'ed to form part of an 'if()' statement in the function itself.

Here's what's in the controller:

$this->form_validation->set_rules('rating', 'Rating','required');
$condition = $this->input->post('rating')  . " != 'Excellent'";
$this->form_validation->set_rules('details', 'Details', 'required_conditional[' . htmlentities($condition) .']');

And here's the callback function itself:

function required_conditional($str, $condition)
{
    if (eval(html_entity_decode($condition))) {
        if ($str == '') {
            $this->set_message('required_conditional', 'The %s field is required');
            return FALSE;
        }
        else {
            return TRUE;
        }
    }
}

Any ideas why it's not working anyone?

Thanks, Matt

+1  A: 

It's because eval evaluates statements, not expressions. This will give you a parse error:

$test = "1 > 0";
if (eval($test)) { echo "echo!"; }

And this will work as you expect it to:

$test = "return 1 > 0;";
if (eval($test)) { echo "echo!"; }
jimyi
OK, so in the case of my example above, I should change $condition to: return $this->input->post('rating') . " != 'Excellent'";??I'd actually created a simplified example there. What I really need to do is this: $condition = "('" . $this->input->post('exterior_condition_rating') . "' != '-1') so how would I get that to work?
Sorry, didn't realise the line breaks would be stripped out. Hope it's still readable!
`$condition = "return ('" . $this->input->post('exterior_condition_rating') . "' != '-1') "`
jimyi
A: 

shouldn't you use "callback_<function name>" ?

Codemaster Snake
I've extended the validation class and included the function in there so there's no need to use the callback_ prefix.
A: 

Yep the correct syntax to call form validation callbacks it to use "callback_"

Timur Asaliev