@@ -86,7 +86,9 @@ public function errors(array $data, $newRecord = true) {
86
86
continue ;
87
87
}
88
88
89
- $ canBeEmpty = $ this ->_canBeEmpty ($ field , $ newRecord );
89
+ $ providers = $ this ->_providers ;
90
+ $ context = compact ('data ' , 'newRecord ' , 'field ' , 'providers ' );
91
+ $ canBeEmpty = $ this ->_canBeEmpty ($ field , $ context );
90
92
$ isEmpty = $ this ->_fieldIsEmpty ($ data [$ name ]);
91
93
92
94
if (!$ canBeEmpty && $ isEmpty ) {
@@ -314,7 +316,7 @@ public function validatePresence($field, $mode = true, $message = null) {
314
316
* This is the opposite of notEmpty() which requires a field to not be empty.
315
317
* By using $mode equal to 'create' or 'update', you can allow fields to be empty
316
318
* when records are first created, or when they are updated.
317
- *
319
+ *
318
320
* ### Example:
319
321
*
320
322
* {{{
@@ -387,7 +389,12 @@ public function allowEmpty($field, $when = true) {
387
389
public function notEmpty ($ field , $ message = null , $ when = false ) {
388
390
if ($ when === 'create ' || $ when === 'update ' ) {
389
391
$ when = $ when === 'create ' ? 'update ' : 'create ' ;
392
+ } elseif (is_callable ($ when )) {
393
+ $ when = function ($ context ) use ($ when ) {
394
+ return !$ when ($ context );
395
+ };
390
396
}
397
+
391
398
$ this ->field ($ field )->isEmptyAllowed ($ when );
392
399
if ($ message ) {
393
400
$ this ->_allowEmptyMessages [$ field ] = $ message ;
@@ -443,11 +450,17 @@ protected function _checkPresence($field, $newRecord) {
443
450
* Returns whether the field can be left blank according to `allowEmpty`
444
451
*
445
452
* @param ValidationSet $field the set of rules for a field
446
- * @param bool $newRecord whether the data to be validated is new or to be updated .
453
+ * @param array $context a key value list of data containing the validation context .
447
454
* @return bool
448
455
*/
449
- protected function _canBeEmpty ($ field , $ newRecord ) {
456
+ protected function _canBeEmpty ($ field , $ context ) {
450
457
$ allowed = $ field ->isEmptyAllowed ();
458
+
459
+ if (!is_string ($ allowed ) && is_callable ($ allowed )) {
460
+ return $ allowed ($ context );
461
+ }
462
+
463
+ $ newRecord = $ context ['newRecord ' ];
451
464
if (in_array ($ allowed , array ('create ' , 'update ' ), true )) {
452
465
$ allowed = (
453
466
($ allowed === 'create ' && $ newRecord ) ||
0 commit comments