1

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

2
  • mind to post some examples of $condition? Commented Sep 1, 2009 at 10:23
  • See the second line in the first code snippet. Commented Sep 1, 2009 at 10:49

3 Answers 3

2

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!"; }
Sign up to request clarification or add additional context in comments.

3 Comments

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') && ('" . $this->input->post('exterior_condition_rating') . "' != '5 - Excellent')"; 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') && ('" . $this->input->post('exterior_condition_rating') . "' != '5 - Excellent');"
2

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

1 Comment

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

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

Comments

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.