ConfirmableBehavior.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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
  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. */
  12. /**
  13. * 2011-07-05 ms
  14. */
  15. class ConfirmableBehavior extends ModelBehavior {
  16. protected $_defaults = array(
  17. 'message' => 'Please confirm the checkbox',
  18. 'field' => 'confirm',
  19. 'model' => null,
  20. 'before' => 'validate',
  21. );
  22. public $settings = array();
  23. public function setup(Model $Model, $settings = array()) {
  24. if (!isset($this->settings[$Model->alias])) {
  25. $this->settings[$Model->alias] = $this->_defaults;
  26. }
  27. $this->settings[$Model->alias] = array_merge($this->settings[$Model->alias], is_array($settings) ? $settings : array());
  28. }
  29. public function beforeValidate(Model $Model) {
  30. $return = parent::beforeValidate($Model);
  31. if ($this->settings[$Model->alias]['before'] == 'validate') {
  32. # we dont want to return the value, because other fields might then not be validated
  33. # (save will not continue with errors, anyway)
  34. $this->confirm($Model, $return);
  35. }
  36. return $return;
  37. }
  38. public function beforeSave(Model $Model) {
  39. $return = parent::beforeSave($Model);
  40. if ($this->settings[$Model->alias]['before'] == 'save') {
  41. return $this->confirm($Model, $return);
  42. }
  43. return $return;
  44. }
  45. /**
  46. * Run before a model is saved, used...
  47. *
  48. * @param object $Model Model about to be saved.
  49. * @return boolean true if save should proceed, false otherwise
  50. * @access public
  51. */
  52. public function confirm(Model $Model, $return = true) {
  53. $field = $this->settings[$Model->alias]['field'];
  54. $message = $this->settings[$Model->alias]['message'];
  55. if (empty($Model->data[$Model->alias][$field])) {
  56. $Model->invalidate($field, $message);
  57. return false;
  58. }
  59. return $return;
  60. }
  61. }