ConfirmableBehavior.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace Tools\Model\Behavior;
  3. use Cake\Event\Event;
  4. use Cake\ORM\Behavior;
  5. use Cake\ORM\Table;
  6. use Cake\Validation\Validator;
  7. /**
  8. * ConfirmableBehavior allows forms to easily require a checkbox toggled (confirmed).
  9. * Example: Terms of use on registration forms or some "confirm delete checkbox"
  10. *
  11. * Copyright 2011, dereuromark (http://www.dereuromark.de)
  12. *
  13. * @link http://github.com/dereuromark/
  14. * @license http://opensource.org/licenses/mit-license.php MIT
  15. * @link http://www.dereuromark.de/2011/07/05/introducing-two-cakephp-behaviors/
  16. */
  17. class ConfirmableBehavior extends Behavior {
  18. /**
  19. * @var array
  20. */
  21. protected $_defaultConfig = [
  22. 'message' => null,
  23. 'field' => 'confirm',
  24. //'table' => null,
  25. 'validator' => 'default',
  26. ];
  27. /**
  28. * @param \Cake\ORM\Table $table
  29. * @param array $config
  30. */
  31. public function __construct(Table $table, array $config = []) {
  32. parent::__construct($table, $config);
  33. if (!$this->_config['message']) {
  34. $this->_config['message'] = __d('tools', 'Please confirm the checkbox');
  35. }
  36. }
  37. /**
  38. * @param \Cake\Event\Event $event
  39. * @param \Cake\Validation\Validator $validator
  40. * @param string $name
  41. */
  42. public function buildValidator(Event $event, Validator $validator, $name) {
  43. $this->build($validator, $name);
  44. }
  45. /**
  46. * @param \Cake\Validation\Validator $validator
  47. * @param string $name
  48. */
  49. public function build(Validator $validator, $name = 'default') {
  50. if ($name !== $this->_config['validator']) {
  51. return;
  52. }
  53. $field = $this->_config['field'];
  54. $message = $this->_config['message'];
  55. $validator->add($field, 'notBlank', [
  56. 'rule' => function ($value, $context) {
  57. return !empty($value);
  58. },
  59. 'message' => $message,
  60. //'provider' => 'table',
  61. 'requirePresence' => true,
  62. 'allowEmpty' => false,
  63. 'last' => true]
  64. );
  65. $validator->requirePresence($field);
  66. //$validator->allowEmpty($field, false);
  67. }
  68. }