문제

I have a question regarding default values for model fields, this problem has been driving me crazy for a while.

To give you an example, I have a model with a status field that must be validated:

$validate = array (
    ...
    'status' => array(
        'list' => array(
            'rule' => array('inList', array('0','1')),
            'allowEmpty' => true
        )
    )
)

The data that is inserted in the database is not submitted from a form.

If the status field is missing, I want it to default to 1, otherwise it must be validated.

Is there a way to do this from the model without using custom validation rules? I know I can set the default value in the MySQL table, but I still want to validate it from the model, in case a different value is submitted.

EDIT

I looked at the Validation class code and the inList validation is just a stupid wrapper for an in_array check:

Cake.Utility.Validation.php

public static function inList($check, $list, $strict = true) {
   return in_array($check, $list, $strict);
}

What do you know, there is also a third param that is not mentioned in the CakePHP Api docs ($strict), which defaults to true.

From the in_array docs:

If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.

It still doesn't solve my problem, but now I know why array('inList', array('0','1')) was not validating empty fields even though allowEmpty was set to true.

Thank you.

도움이 되었습니까?

해결책

You can use the beforeSave method to set a default value. Don't forget to return true or you will abort the save.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top