ConfirmableBehavior.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 $settings = array();
  22. public function setup(Model $Model, $settings = array()) {
  23. if (!isset($this->settings[$Model->alias])) {
  24. $this->settings[$Model->alias] = $this->_defaults;
  25. }
  26. $this->settings[$Model->alias] = array_merge($this->settings[$Model->alias], is_array($settings) ? $settings : array());
  27. }
  28. /**
  29. * ConfirmableBehavior::beforeValidate()
  30. *
  31. * @param mixed $Model
  32. * @return bool $success
  33. */
  34. public function beforeValidate(Model $Model) {
  35. $return = parent::beforeValidate($Model);
  36. if ($this->settings[$Model->alias]['before'] == 'validate') {
  37. # we dont want to return the value, because other fields might then not be validated
  38. # (save will not continue with errors, anyway)
  39. $this->confirm($Model, $return);
  40. }
  41. return $return;
  42. }
  43. /**
  44. * ConfirmableBehavior::beforeSave()
  45. *
  46. * @param mixed $Model
  47. * @return mixed
  48. */
  49. public function beforeSave(Model $Model) {
  50. $return = parent::beforeSave($Model);
  51. if ($this->settings[$Model->alias]['before'] == 'save') {
  52. return $this->confirm($Model, $return);
  53. }
  54. return $return;
  55. }
  56. /**
  57. * The actual logic
  58. *
  59. * @param object $Model Model about to be saved.
  60. * @return boolean true if save should proceed, false otherwise
  61. * @access public
  62. */
  63. public function confirm(Model $Model, $return = true) {
  64. $field = $this->settings[$Model->alias]['field'];
  65. $message = $this->settings[$Model->alias]['message'];
  66. if (empty($Model->data[$Model->alias][$field])) {
  67. $Model->invalidate($field, $message);
  68. return false;
  69. }
  70. return $return;
  71. }
  72. }