confirmable.php 1.9 KB

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