ConfirmableBehavior.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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://www.opensource.org/licenses/mit-license.php The MIT License
  11. * @link http://www.dereuromark.de/2011/07/05/introducing-two-cakephp-behaviors/
  12. * 2011-07-05 ms
  13. */
  14. class ConfirmableBehavior extends ModelBehavior {
  15. protected $_defaults = array(
  16. 'message' => 'Please confirm the checkbox',
  17. 'field' => 'confirm',
  18. 'model' => null,
  19. 'before' => 'validate',
  20. );
  21. public function setup(Model $Model, $settings = array()) {
  22. if (!isset($this->settings[$Model->alias])) {
  23. $this->settings[$Model->alias] = $this->_defaults;
  24. }
  25. $this->settings[$Model->alias] = array_merge($this->settings[$Model->alias], is_array($settings) ? $settings : array());
  26. }
  27. /**
  28. * ConfirmableBehavior::beforeValidate()
  29. *
  30. * @param mixed $Model
  31. * @return bool $success
  32. */
  33. public function beforeValidate(Model $Model) {
  34. $return = parent::beforeValidate($Model);
  35. if ($this->settings[$Model->alias]['before'] === 'validate') {
  36. # we dont want to return the value, because other fields might then not be validated
  37. # (save will not continue with errors, anyway)
  38. $this->confirm($Model, $return);
  39. }
  40. return $return;
  41. }
  42. /**
  43. * ConfirmableBehavior::beforeSave()
  44. *
  45. * @param mixed $Model
  46. * @return mixed
  47. */
  48. public function beforeSave(Model $Model) {
  49. $return = parent::beforeSave($Model);
  50. if ($this->settings[$Model->alias]['before'] === 'save') {
  51. return $this->confirm($Model, $return);
  52. }
  53. return $return;
  54. }
  55. /**
  56. * The actual logic
  57. *
  58. * @param object $Model Model about to be saved.
  59. * @return boolean true if save should proceed, false otherwise
  60. * @access public
  61. */
  62. public function confirm(Model $Model, $return = true) {
  63. $field = $this->settings[$Model->alias]['field'];
  64. $message = $this->settings[$Model->alias]['message'];
  65. if (empty($Model->data[$Model->alias][$field])) {
  66. $Model->invalidate($field, __($message));
  67. return false;
  68. }
  69. return $return;
  70. }
  71. }