ConfirmableBehavior.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. App::uses('ModelBehavior', 'Model');
  3. /**
  4. * ConfirmableBehavior allows forms to easily require a checkbox toggled (confirmed).
  5. * Example: Terms of use on registration forms or some "confirm delete checkbox"
  6. *
  7. * Copyright 2011, dereuromark (http://www.dereuromark.de)
  8. *
  9. * @link http://github.com/dereuromark/
  10. * @license http://opensource.org/licenses/mit-license.php MIT
  11. * @link http://www.dereuromark.de/2011/07/05/introducing-two-cakephp-behaviors/
  12. */
  13. class ConfirmableBehavior extends ModelBehavior {
  14. protected $_defaultConfig = [
  15. 'message' => 'Please confirm the checkbox',
  16. 'field' => 'confirm',
  17. 'model' => null,
  18. 'before' => 'validate',
  19. ];
  20. public function setup(Model $Model, $config = []) {
  21. if (!isset($this->settings[$Model->alias])) {
  22. $this->settings[$Model->alias] = $this->_defaultConfig;
  23. }
  24. $this->settings[$Model->alias] = $config + $this->settings[$Model->alias];
  25. }
  26. /**
  27. * ConfirmableBehavior::beforeValidate()
  28. *
  29. * @param Model $Model
  30. * @return bool Success
  31. */
  32. public function beforeValidate(Model $Model, $options = []) {
  33. $return = parent::beforeValidate($Model, $options);
  34. if ($this->settings[$Model->alias]['before'] === 'validate') {
  35. // we dont want to return the value, because other fields might then not be validated
  36. // (save will not continue with errors, anyway)
  37. $this->confirm($Model, $return);
  38. }
  39. return $return;
  40. }
  41. /**
  42. * ConfirmableBehavior::beforeSave()
  43. *
  44. * @param Model $Model
  45. * @return mixed
  46. */
  47. public function beforeSave(Model $Model, $options = []) {
  48. $return = parent::beforeSave($Model, $options);
  49. if ($this->settings[$Model->alias]['before'] === 'save') {
  50. return $this->confirm($Model, $return);
  51. }
  52. return $return;
  53. }
  54. /**
  55. * The actual logic
  56. *
  57. * @param Model $Model Model about to be saved.
  58. * @return bool true if save should proceed, false otherwise
  59. */
  60. public function confirm(Model $Model, $return = true) {
  61. $field = $this->settings[$Model->alias]['field'];
  62. $message = $this->settings[$Model->alias]['message'];
  63. if (empty($Model->data[$Model->alias][$field])) {
  64. $Model->invalidate($field, __d('tools', $message));
  65. return false;
  66. }
  67. return $return;
  68. }
  69. }