Skip to content

Instantly share code, notes, and snippets.

@hmic
Last active November 6, 2017 18:19
Show Gist options
  • Save hmic/e3e6abaaa6cb00a09ae9949a56ef5b5a to your computer and use it in GitHub Desktop.
Save hmic/e3e6abaaa6cb00a09ae9949a56ef5b5a to your computer and use it in GitHub Desktop.
CakePHP, dependent, multiple fields, validation example
<?php
class ATable extends \Cake\ORM\Table
{
public function validationDefault(Validator $validator)
{
$fields = ['salutation', 'firstname', 'lastname'];
$validator
->provider('allEmptyOrFilled', $fields);
foreach($fields as $field) {
$validator
->scalar($field)
->requirePresence($field, 'create')
->allowEmpty($field, function(array $context) {
return $this->validateAllEmptyOrFilled($context);
})
->add($field, 'allEmptyOrFilled', [
'rule' => function($value, $context) {
return !empty($value) && $this->validateAllEmptyOrFilled($context);
},
'message' => __('Enter a salutation, firstname and lastname or leave all 3 empty.'),
]);
}
return $validator;
}
protected function countEmptyFields($data, $fields)
{
$empty_fields = 0;
foreach($fields as $field) {
if(
is_array($data) && !array_key_exists($field, $data) ||
!is_array($data) && !isset($data->$field)
) {
return false;
}
if(
is_array($data) && empty($data[$field]) ||
!is_array($data) && empty($data->$field)
) {
$empty_fields++;
}
}
return $empty_fields;
}
public function validateAllEmptyOrFilled($context)
{
if(!array_key_exists('allEmptyOrFilled', $context['providers'])) {
return false;
}
$fields = $context['providers']['allEmptyOrFilled'];
$empty_fields = $this->countEmptyFields($context['data'], $fields);
return $empty_fields === 0 || $empty_fields === count($fields);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment