0
votes

Heres the problem

I want to require a field (litters_per_year) only if another field that is a checkbox is checked. When I do this, cake is trying to force me to put a value into the field and I don't know why. I have tried setting required & allowEmpty to false & true respectively, but then my custom rule does not run.

Heres the code

NOTE: The details of the following code aren't that important - they are here to provide a scenario.

I have the following code in my VIEW which works fine:

echo $this->Form->input('litters_per_year', array(
    'label' => 'Litters per year (average)'
));

I have the following code in my MODEL's public $validate:

'litters_per_year' => array(
    'isNeeded' => array(
        'rule' => array('isNeeded', 'litters_per_year'),
        'message' => 'Please enter the litters per year average'
    )
)

which is calling the custom validation method

public function isNeeded($field) {
    // Check if a checkbox is checked right here
    // Assume it is not... return false
    return false;
}

It returns false for simplicity to solve this issue.

Let's assume that the checkbox field is named 'the_checkbox'.

1

1 Answers

1
votes

At the moment your field should always fail validation, since you return false from isNeeded.

To make it work as you expect, do something like this:
(Note: replace 'ModelName' with your model name)

public function isNeeded($field) {
    if ($this->data['ModelName']['the_checkbox']) {
        // Checkbox is checked, so we have to require litters per year
        if (empty($field)) {
            // They have checked the box but have NOT entered litters_per_year
            // so we have a problem. NOT VALID!
            return false;
        } else {
            // They have checked the box, and entered a litters_per_year
            // value, so all good! Everything is valid!
            return true;
        }
    } else {
        // Checkbox is not checked, so we don't care what 
        // the field contains - it is always valid.
        return true;
    }
}

Or, without the needless verbosity, this should work:

public function isNeeded($field) {
    if ($this->data['ModelName']['the_checkbox']) {
        return $field;
    } else {
        return true;
    }
}

In this example, if the checkbox is checked, validation will pass if $field is truthy, and fail if it is falsey.