ConfirmableBehavior.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * ConfirmableBehavior allows forms to easily require a checkbox toggled (confirmed)
  4. * example: terms of use on registration
  5. *
  6. * Copyright 2011, dereuromark (http://www.dereuromark.de)
  7. *
  8. * @link http://github.com/dereuromark/
  9. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  10. */
  11. /**
  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. public function beforeValidate(Model $Model) {
  29. $return = parent::beforeValidate($Model);
  30. if ($this->settings[$Model->alias]['before'] == 'validate') {
  31. # we dont want to return the value, because other fields might then not be validated
  32. # (save will not continue with errors, anyway)
  33. $this->confirm($Model, $return);
  34. }
  35. return $return;
  36. }
  37. public function beforeSave(Model $Model) {
  38. $return = parent::beforeSave($Model);
  39. if ($this->settings[$Model->alias]['before'] == 'save') {
  40. return $this->confirm($Model, $return);
  41. }
  42. return $return;
  43. }
  44. /**
  45. * Run before a model is saved, used...
  46. *
  47. * @param object $Model Model about to be saved.
  48. * @return boolean true if save should proceed, false otherwise
  49. * @access public
  50. */
  51. public function confirm(Model $Model, $return = true) {
  52. $field = $this->settings[$Model->alias]['field'];
  53. $message = $this->settings[$Model->alias]['message'];
  54. if (empty($Model->data[$Model->alias][$field])) {
  55. $Model->invalidate($field, $message);
  56. return false;
  57. }
  58. return $return;
  59. }
  60. }