Note that there are some explanatory texts on larger screens.

plurals
  1. PODefault value for a model validate rule
    primarykey
    data
    text
    <p>I have a question regarding default values for model fields, this problem has been driving me crazy for a while.</p> <p>To give you an example, I have a model with a status field that must be validated:</p> <pre><code>$validate = array ( ... 'status' =&gt; array( 'list' =&gt; array( 'rule' =&gt; array('inList', array('0','1')), 'allowEmpty' =&gt; true ) ) ) </code></pre> <p>The data that is inserted in the database is not submitted from a form.</p> <p>If the status field is missing, I want it to default to 1, otherwise it must be validated. </p> <p>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.</p> <p><strong>EDIT</strong></p> <p>I looked at the Validation class code and the inList validation is just a stupid wrapper for an in_array check:</p> <p><strong>Cake.Utility.Validation.php</strong></p> <pre><code>public static function inList($check, $list, $strict = true) { return in_array($check, $list, $strict); } </code></pre> <p>What do you know, there is also a third param that is not mentioned in the <a href="http://api21.cakephp.org/class/validation#method-ValidationinList" rel="nofollow"><code>CakePHP Api docs</code></a> ($strict), which defaults to true.</p> <p>From the in_array docs:</p> <blockquote> <p>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.</p> </blockquote> <p>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.</p> <p>Thank you.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload