ConfirmableBehavior.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 Model $Model
  31. * @return boolean Success
  32. */
  33. public function beforeValidate(Model $Model, $options = array()) {
  34. $return = parent::beforeValidate($Model, $options);
  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 Model $Model
  46. * @return mixed
  47. */
  48. public function beforeSave(Model $Model, $options = array()) {
  49. $return = parent::beforeSave($Model, $options);
  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. */
  61. public function confirm(Model $Model, $return = true) {
  62. $field = $this->settings[$Model->alias]['field'];
  63. $message = $this->settings[$Model->alias]['message'];
  64. if (empty($Model->data[$Model->alias][$field])) {
  65. $Model->invalidate($field, __($message));
  66. return false;
  67. }
  68. return $return;
  69. }
  70. }