3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * This is our base form. It is part of the Form/Controller/StateMachine
30 * trifecta. Each form is associated with a specific state in the state
31 * machine. Each form can also operate in various modes
34 * @copyright CiviCRM LLC (c) 2004-2015
39 require_once 'HTML/QuickForm/Page.php';
44 class CRM_Core_Form
extends HTML_QuickForm_Page
{
47 * The state object that this form belongs to
53 * The name of this form
59 * The title of this form
62 protected $_title = NULL;
65 * The options passed into this form
68 protected $_options = NULL;
71 * The mode of operation for this form
77 * Available payment processors.
79 * As part of trying to consolidate various payment pages we store processors here & have functions
80 * at this level to manage them.
83 * An array of payment processor details with objects loaded in the 'object' field.
85 protected $_paymentProcessors;
88 * Available payment processors (IDS).
90 * As part of trying to consolidate various payment pages we store processors here & have functions
91 * at this level to manage them.
94 * An array of the IDS available on this form.
96 public $_paymentProcessorIDs;
99 * The renderer used for this form
103 protected $_renderer;
106 * An array to hold a list of datefields on the form
107 * so that they can be converted to ISO in a consistent manner
111 * e.g on a form declare $_dateFields = array(
112 * 'receive_date' => array('default' => 'now'),
114 * then in postProcess call $this->convertDateFieldsToMySQL($formValues)
115 * to have the time field re-incorporated into the field & 'now' set if
116 * no value has been passed in
118 protected $_dateFields = array();
121 * Cache the smarty template for efficiency reasons
123 * @var CRM_Core_Smarty
125 static protected $_template;
128 * Indicate if this form should warn users of unsaved changes
130 protected $unsavedChangesWarn;
133 * What to return to the client if in ajax mode (snippet=json)
137 public $ajaxResponse = array();
140 * Url path used to reach this page
144 public $urlPath = array();
147 * @var CRM_Core_Controller
152 * Constants for attributes for various form elements
153 * attempt to standardize on the number of variations that we
154 * use of the below form elements
158 const ATTR_SPACING
= ' ';
161 * All checkboxes are defined with a common prefix. This allows us to
162 * have the same javascript to check / clear all the checkboxes etc
163 * If u have multiple groups of checkboxes, you will need to give them different
164 * ids to avoid potential name collision
168 const CB_PREFIX
= 'mark_x_', CB_PREFIY
= 'mark_y_', CB_PREFIZ
= 'mark_z_', CB_PREFIX_LEN
= 7;
171 * @internal to keep track of chain-select fields
174 private $_chainSelectFields = array();
177 * Constructor for the basic form page.
179 * We should not use QuickForm directly. This class provides a lot
180 * of default convenient functions, rules and buttons
182 * @param object $state
183 * State associated with this form.
184 * @param \const|\enum|int $action The mode the form is operating in (None/Create/View/Update/Delete)
185 * @param string $method
186 * The type of http method used (GET/POST).
187 * @param string $name
188 * The name of the form if different from class name.
190 * @return \CRM_Core_Form
192 public function __construct(
194 $action = CRM_Core_Action
::NONE
,
200 $this->_name
= $name;
203 // CRM-15153 - FIXME this name translates to a DOM id and is not always unique!
204 $this->_name
= CRM_Utils_String
::getClassName(CRM_Utils_System
::getClassName($this));
207 $this->HTML_QuickForm_Page($this->_name
, $method);
209 $this->_state
=& $state;
211 $this->_state
->setName($this->_name
);
213 $this->_action
= (int) $action;
215 $this->registerRules();
217 // let the constructor initialize this, should happen only once
218 if (!isset(self
::$_template)) {
219 self
::$_template = CRM_Core_Smarty
::singleton();
221 // Workaround for CRM-15153 - give each form a reasonably unique css class
222 $this->addClass(CRM_Utils_System
::getClassName($this));
224 $this->assign('snippet', CRM_Utils_Array
::value('snippet', $_GET));
227 public static function generateID() {
231 * Add one or more css classes to the form
232 * @param string $className
234 public function addClass($className) {
235 $classes = $this->getAttribute('class');
236 $this->setAttribute('class', ($classes ?
"$classes " : '') . $className);
240 * Register all the standard rules that most forms potentially use.
244 public function registerRules() {
245 static $rules = array(
273 foreach ($rules as $rule) {
274 $this->registerRule($rule, 'callback', $rule, 'CRM_Utils_Rule');
279 * Simple easy to use wrapper around addElement. Deal with
280 * simple validation rules
282 * @param string $type
283 * @param string $name
284 * @param string $label
285 * @param string|array $attributes (options for select elements)
286 * @param bool $required
287 * @param array $extra
288 * (attributes for select elements).
290 * @return HTML_QuickForm_Element could be an error object
292 public function &add(
293 $type, $name, $label = '',
294 $attributes = '', $required = FALSE, $extra = NULL
296 if ($type == 'wysiwyg') {
297 $attributes = ($attributes ?
$attributes : array()) +
array('class' => '');
298 $attributes['class'] .= ' crm-form-wysiwyg';
301 if ($type == 'select' && is_array($extra)) {
302 // Normalize this property
303 if (!empty($extra['multiple'])) {
304 $extra['multiple'] = 'multiple';
307 unset($extra['multiple']);
309 // Add placeholder option for select
310 if (isset($extra['placeholder'])) {
311 if ($extra['placeholder'] === TRUE) {
312 $extra['placeholder'] = $required ?
ts('- select -') : ts('- none -');
314 if (($extra['placeholder'] ||
$extra['placeholder'] === '') && empty($extra['multiple']) && is_array($attributes) && !isset($attributes[''])) {
315 $attributes = array('' => $extra['placeholder']) +
$attributes;
319 $element = $this->addElement($type, $name, $label, $attributes, $extra);
320 if (HTML_QuickForm
::isError($element)) {
321 CRM_Core_Error
::fatal(HTML_QuickForm
::errorMessage($element));
325 if ($type == 'file') {
326 $error = $this->addRule($name, ts('%1 is a required field.', array(1 => $label)), 'uploadedfile');
329 $error = $this->addRule($name, ts('%1 is a required field.', array(1 => $label)), 'required');
331 if (HTML_QuickForm
::isError($error)) {
332 CRM_Core_Error
::fatal(HTML_QuickForm
::errorMessage($element));
340 * called before buildForm. Any pre-processing that
341 * needs to be done for buildForm should be done here
343 * This is a virtual function and should be redefined if needed
348 public function preProcess() {
352 * called after the form is validated. Any
353 * processing of form state etc should be done in this function.
354 * Typically all processing associated with a form should be done
355 * here and relevant state should be stored in the session
357 * This is a virtual function and should be redefined if needed
362 public function postProcess() {
366 * just a wrapper, so that we can call all the hook functions
367 * @param bool $allowAjax
368 * FIXME: This feels kind of hackish, ideally we would take the json-related code from this function.
369 * and bury it deeper down in the controller
371 public function mainProcess($allowAjax = TRUE) {
372 $this->postProcess();
373 $this->postProcessHook();
375 // Respond with JSON if in AJAX context (also support legacy value '6')
376 if ($allowAjax && !empty($_REQUEST['snippet']) && in_array($_REQUEST['snippet'], array(
377 CRM_Core_Smarty
::PRINT_JSON
,
381 $this->ajaxResponse
['buttonName'] = str_replace('_qf_' . $this->getAttribute('id') . '_', '', $this->controller
->getButtonName());
382 $this->ajaxResponse
['action'] = $this->_action
;
383 if (isset($this->_id
) ||
isset($this->id
)) {
384 $this->ajaxResponse
['id'] = isset($this->id
) ?
$this->id
: $this->_id
;
386 CRM_Core_Page_AJAX
::returnJsonResponse($this->ajaxResponse
);
391 * The postProcess hook is typically called by the framework.
392 * However in a few cases, the form exits or redirects early in which
393 * case it needs to call this function so other modules can do the needful
394 * Calling this function directly should be avoided if possible. In general a
395 * better way is to do setUserContext so the framework does the redirect
397 public function postProcessHook() {
398 CRM_Utils_Hook
::postProcess(get_class($this), $this);
402 * This virtual function is used to build the form. It replaces the
403 * buildForm associated with QuickForm_Page. This allows us to put
404 * preProcess in front of the actual form building routine
409 public function buildQuickForm() {
413 * This virtual function is used to set the default values of
414 * various form elements
419 * reference to the array of default values
421 public function setDefaultValues() {
426 * This is a virtual function that adds group and global rules to
427 * the form. Keeping it distinct from the form to keep code small
428 * and localized in the form building code
433 public function addRules() {
437 * Performs the server side validation.
440 * true if no error found
441 * @throws HTML_QuickForm_Error
443 public function validate() {
444 $error = parent
::validate();
446 $this->validateChainSelectFields();
448 $hookErrors = CRM_Utils_Hook
::validate(
450 $this->_submitValues
,
455 if (!is_array($hookErrors)) {
456 $hookErrors = array();
459 CRM_Utils_Hook
::validateForm(
461 $this->_submitValues
,
467 if (!empty($hookErrors)) {
468 $this->_errors +
= $hookErrors;
471 return (0 == count($this->_errors
));
475 * Core function that builds the form. We redefine this function
476 * here and expect all CRM forms to build their form in the function
479 public function buildForm() {
480 $this->_formBuilt
= TRUE;
484 CRM_Utils_Hook
::preProcess(get_class($this), $this);
486 $this->assign('translatePermission', CRM_Core_Permission
::check('translate CiviCRM'));
489 $this->controller
->_key
&&
490 $this->controller
->_generateQFKey
492 $this->addElement('hidden', 'qfKey', $this->controller
->_key
);
493 $this->assign('qfKey', $this->controller
->_key
);
497 // _generateQFKey suppresses the qfKey generation on form snippets that
498 // are part of other forms, hence we use that to avoid adding entryURL
499 if ($this->controller
->_generateQFKey
&& $this->controller
->_entryURL
) {
500 $this->addElement('hidden', 'entryURL', $this->controller
->_entryURL
);
503 $this->buildQuickForm();
505 $defaults = $this->setDefaultValues();
506 unset($defaults['qfKey']);
508 if (!empty($defaults)) {
509 $this->setDefaults($defaults);
512 // call the form hook
513 // also call the hook function so any modules can set their own custom defaults
514 // the user can do both the form and set default values with this hook
515 CRM_Utils_Hook
::buildForm(get_class($this), $this);
519 //Set html data-attribute to enable warning user of unsaved changes
520 if ($this->unsavedChangesWarn
=== TRUE
521 ||
(!isset($this->unsavedChangesWarn
)
522 && ($this->_action
& CRM_Core_Action
::ADD ||
$this->_action
& CRM_Core_Action
::UPDATE
)
525 $this->setAttribute('data-warn-changes', 'true');
530 * Add default Next / Back buttons
532 * @param array $params
533 * Array of associative arrays in the order in which the buttons should be
534 * displayed. The associate array has 3 fields: 'type', 'name' and 'isDefault'
535 * The base form class will define a bunch of static arrays for commonly used
540 public function addButtons($params) {
541 $prevnext = $spacing = array();
542 foreach ($params as $button) {
543 $attrs = array('class' => 'crm-form-submit') +
(array) CRM_Utils_Array
::value('js', $button);
545 if (!empty($button['class'])) {
546 $attrs['class'] .= ' ' . $button['class'];
549 if (!empty($button['isDefault'])) {
550 $attrs['class'] .= ' default';
553 if (in_array($button['type'], array('upload', 'next', 'submit', 'done', 'process', 'refresh'))) {
554 $attrs['class'] .= ' validate';
555 $defaultIcon = 'check';
558 $attrs['class'] .= ' cancel';
559 $defaultIcon = $button['type'] == 'back' ?
'triangle-1-w' : 'close';
562 if ($button['type'] === 'reset') {
563 $prevnext[] = $this->createElement($button['type'], 'reset', $button['name'], $attrs);
566 if (!empty($button['subName'])) {
567 if ($button['subName'] == 'new') {
568 $defaultIcon = 'plus';
570 if ($button['subName'] == 'done') {
571 $defaultIcon = 'circle-check';
573 if ($button['subName'] == 'next') {
574 $defaultIcon = 'circle-triangle-e';
578 if (in_array($button['type'], array('next', 'upload', 'done')) && $button['name'] === ts('Save')) {
579 $attrs['accesskey'] = 'S';
581 $icon = CRM_Utils_Array
::value('icon', $button, $defaultIcon);
583 $attrs['crm-icon'] = $icon;
585 $buttonName = $this->getButtonName($button['type'], CRM_Utils_Array
::value('subName', $button));
586 $prevnext[] = $this->createElement('submit', $buttonName, $button['name'], $attrs);
588 if (!empty($button['isDefault'])) {
589 $this->setDefaultAction($button['type']);
592 // if button type is upload, set the enctype
593 if ($button['type'] == 'upload') {
594 $this->updateAttributes(array('enctype' => 'multipart/form-data'));
595 $this->setMaxFileSize();
598 // hack - addGroup uses an array to express variable spacing, read from the last element
599 $spacing[] = CRM_Utils_Array
::value('spacing', $button, self
::ATTR_SPACING
);
601 $this->addGroup($prevnext, 'buttons', '', $spacing, FALSE);
605 * Getter function for Name.
609 public function getName() {
614 * Getter function for State.
618 public function &getState() {
619 return $this->_state
;
623 * Getter function for StateType.
627 public function getStateType() {
628 return $this->_state
->getType();
632 * Getter function for title. Should be over-ridden by derived class
636 public function getTitle() {
637 return $this->_title ?
$this->_title
: ts('ERROR: Title is not Set');
641 * Setter function for title.
643 * @param string $title
644 * The title of the form.
646 public function setTitle($title) {
647 $this->_title
= $title;
651 * Assign billing type id to bltID.
653 * @throws CRM_Core_Exception
655 public function assignBillingType() {
656 $this->_bltID
= CRM_Core_BAO_Location
::getBillingLocationId();
657 $this->set('bltID', $this->_bltID
);
658 $this->assign('bltID', $this->_bltID
);
662 * This if a front end form function for setting the payment processor.
664 * It would be good to sync it with the back-end function on abstractEditPayment & use one everywhere.
666 * @throws \CRM_Core_Exception
668 protected function assignPaymentProcessor() {
669 $this->_paymentProcessors
= CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors(
670 array(ucfirst($this->_mode
) . 'Mode'),
671 $this->_paymentProcessorIDs
674 if (!empty($this->_paymentProcessors
)) {
675 foreach ($this->_paymentProcessors
as $paymentProcessorID => $paymentProcessorDetail) {
676 if (empty($this->_paymentProcessor
) && $paymentProcessorDetail['is_default'] == 1 ||
(count($this->_paymentProcessors
) == 1)
678 $this->_paymentProcessor
= $paymentProcessorDetail;
679 $this->assign('paymentProcessor', $this->_paymentProcessor
);
680 // Setting this is a bit of a legacy overhang.
681 $this->_paymentObject
= $paymentProcessorDetail['object'];
684 // It's not clear why we set this on the form.
685 $this->set('paymentProcessors', $this->_paymentProcessors
);
688 throw new CRM_Core_Exception(ts('A payment processor configured for this page might be disabled (contact the site administrator for assistance).'));
693 * Handle Payment Processor switching for contribution and event registration forms.
695 * This function is shared between contribution & event forms & this is their common class.
697 * However, this should be seen as an in-progress refactor, the end goal being to also align the
698 * backoffice forms that action payments.
700 * This function overlaps assignPaymentProcessor, in a bad way.
702 protected function preProcessPaymentOptions() {
703 $this->_paymentProcessorID
= NULL;
704 if ($this->_paymentProcessors
) {
705 if (!empty($this->_submitValues
)) {
706 $this->_paymentProcessorID
= CRM_Utils_Array
::value('payment_processor_id', $this->_submitValues
);
707 $this->_paymentProcessor
= CRM_Utils_Array
::value($this->_paymentProcessorID
, $this->_paymentProcessors
);
708 $this->set('type', $this->_paymentProcessorID
);
709 $this->set('mode', $this->_mode
);
710 $this->set('paymentProcessor', $this->_paymentProcessor
);
712 // Set default payment processor
714 foreach ($this->_paymentProcessors
as $values) {
715 if (!empty($values['is_default']) ||
count($this->_paymentProcessors
) == 1) {
716 $this->_paymentProcessorID
= $values['id'];
721 if ($this->_paymentProcessorID
) {
722 CRM_Core_Payment_ProcessorForm
::preProcess($this);
725 $this->_paymentProcessor
= array();
727 CRM_Financial_Form_Payment
::addCreditCardJs();
729 $this->assign('paymentProcessorID', $this->_paymentProcessorID
);
733 * Setter function for options.
735 * @param mixed $options
739 public function setOptions($options) {
740 $this->_options
= $options;
744 * Getter function for link.
748 public function getLink() {
749 $config = CRM_Core_Config
::singleton();
750 return CRM_Utils_System
::url($_GET[$config->userFrameworkURLVar
],
751 '_qf_' . $this->_name
. '_display=true'
756 * Boolean function to determine if this is a one form page.
760 public function isSimpleForm() {
761 return $this->_state
->getType() & (CRM_Core_State
::START | CRM_Core_State
::FINISH
);
765 * Getter function for Form Action.
769 public function getFormAction() {
770 return $this->_attributes
['action'];
774 * Setter function for Form Action.
776 * @param string $action
780 public function setFormAction($action) {
781 $this->_attributes
['action'] = $action;
785 * Render form and return contents.
789 public function toSmarty() {
790 $this->preProcessChainSelectFields();
791 $renderer = $this->getRenderer();
792 $this->accept($renderer);
793 $content = $renderer->toArray();
794 $content['formName'] = $this->getName();
796 $content['formClass'] = CRM_Utils_System
::getClassName($this);
801 * Getter function for renderer. If renderer is not set
802 * create one and initialize it
806 public function &getRenderer() {
807 if (!isset($this->_renderer
)) {
808 $this->_renderer
= CRM_Core_Form_Renderer
::singleton();
810 return $this->_renderer
;
814 * Use the form name to create the tpl file name.
818 public function getTemplateFileName() {
819 $ext = CRM_Extension_System
::singleton()->getMapper();
820 if ($ext->isExtensionClass(CRM_Utils_System
::getClassName($this))) {
821 $filename = $ext->getTemplateName(CRM_Utils_System
::getClassName($this));
822 $tplname = $ext->getTemplatePath(CRM_Utils_System
::getClassName($this)) . DIRECTORY_SEPARATOR
. $filename;
826 CRM_Utils_System
::getClassName($this),
828 '_' => DIRECTORY_SEPARATOR
,
829 '\\' => DIRECTORY_SEPARATOR
,
837 * A wrapper for getTemplateFileName that includes calling the hook to
838 * prevent us from having to copy & paste the logic of calling the hook
840 public function getHookedTemplateFileName() {
841 $pageTemplateFile = $this->getTemplateFileName();
842 CRM_Utils_Hook
::alterTemplateFile(get_class($this), $this, 'page', $pageTemplateFile);
843 return $pageTemplateFile;
847 * Default extra tpl file basically just replaces .tpl with .extra.tpl
848 * i.e. we dont override
852 public function overrideExtraTemplateFileName() {
857 * Error reporting mechanism.
859 * @param string $message
863 * @param CRM_Core_DAO $dao
864 * A data access object on which we perform a rollback if non - empty.
868 public function error($message, $code = NULL, $dao = NULL) {
870 $dao->query('ROLLBACK');
873 $error = CRM_Core_Error
::singleton();
875 $error->push($code, $message);
879 * Store the variable with the value in the form scope.
881 * @param string $name
882 * Name of the variable.
883 * @param mixed $value
884 * Value of the variable.
888 public function set($name, $value) {
889 $this->controller
->set($name, $value);
893 * Get the variable from the form scope.
895 * @param string $name
896 * Name of the variable
900 public function get($name) {
901 return $this->controller
->get($name);
909 public function getAction() {
910 return $this->_action
;
917 * The mode we want to set the form.
921 public function setAction($action) {
922 $this->_action
= $action;
926 * Assign value to name in template.
930 * @param mixed $value
935 public function assign($var, $value = NULL) {
936 self
::$_template->assign($var, $value);
940 * Assign value to name in template by reference.
944 * @param mixed $value
949 public function assign_by_ref($var, &$value) {
950 self
::$_template->assign_by_ref($var, $value);
954 * Appends values to template variables.
956 * @param array|string $tpl_var the template variable name(s)
957 * @param mixed $value
958 * The value to append.
961 public function append($tpl_var, $value = NULL, $merge = FALSE) {
962 self
::$_template->append($tpl_var, $value, $merge);
966 * Returns an array containing template variables.
968 * @param string $name
972 public function get_template_vars($name = NULL) {
973 return self
::$_template->get_template_vars($name);
977 * @param string $name
980 * @param array $attributes
981 * @param null $separator
982 * @param bool $required
984 * @return HTML_QuickForm_group
986 public function &addRadio($name, $title, $values, $attributes = array(), $separator = NULL, $required = FALSE) {
988 $attributes = $attributes ?
$attributes : array();
989 $allowClear = !empty($attributes['allowClear']);
990 unset($attributes['allowClear']);
991 $attributes['id_suffix'] = $name;
992 foreach ($values as $key => $var) {
993 $options[] = $this->createElement('radio', NULL, NULL, $var, $key, $attributes);
995 $group = $this->addGroup($options, $name, $title, $separator);
997 $this->addRule($name, ts('%1 is a required field.', array(1 => $title)), 'required');
1000 $group->setAttribute('allowClear', TRUE);
1008 * @param bool $allowClear
1009 * @param null $required
1010 * @param array $attributes
1012 public function addYesNo($id, $title, $allowClear = FALSE, $required = NULL, $attributes = array()) {
1013 $attributes +
= array('id_suffix' => $id);
1015 $choice[] = $this->createElement('radio', NULL, '11', ts('Yes'), '1', $attributes);
1016 $choice[] = $this->createElement('radio', NULL, '11', ts('No'), '0', $attributes);
1018 $group = $this->addGroup($choice, $id, $title);
1020 $group->setAttribute('allowClear', TRUE);
1023 $this->addRule($id, ts('%1 is a required field.', array(1 => $title)), 'required');
1031 * @param null $other
1032 * @param null $attributes
1033 * @param null $required
1034 * @param null $javascriptMethod
1035 * @param string $separator
1036 * @param bool $flipValues
1038 public function addCheckBox(
1039 $id, $title, $values, $other = NULL,
1040 $attributes = NULL, $required = NULL,
1041 $javascriptMethod = NULL,
1042 $separator = '<br />', $flipValues = FALSE
1046 if ($javascriptMethod) {
1047 foreach ($values as $key => $var) {
1049 $options[] = $this->createElement('checkbox', $var, NULL, $key, $javascriptMethod);
1052 $options[] = $this->createElement('checkbox', $key, NULL, $var, $javascriptMethod);
1057 foreach ($values as $key => $var) {
1059 $options[] = $this->createElement('checkbox', $var, NULL, $key);
1062 $options[] = $this->createElement('checkbox', $key, NULL, $var);
1067 $this->addGroup($options, $id, $title, $separator);
1070 $this->addElement('text', $id . '_other', ts('Other'), $attributes[$id . '_other']);
1075 ts('%1 is a required field.', array(1 => $title)),
1081 public function resetValues() {
1082 $data = $this->controller
->container();
1083 $data['values'][$this->_name
] = array();
1087 * Simple shell that derived classes can call to add buttons to
1088 * the form with a customized title for the main Submit
1090 * @param string $title
1091 * Title of the main button.
1092 * @param string $nextType
1093 * Button type for the form after processing.
1094 * @param string $backType
1095 * @param bool|string $submitOnce If true, add javascript to next button submit which prevents it from being clicked more than once
1099 public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
1101 if ($backType != NULL) {
1103 'type' => $backType,
1104 'name' => ts('Previous'),
1107 if ($nextType != NULL) {
1108 $nextButton = array(
1109 'type' => $nextType,
1111 'isDefault' => TRUE,
1114 $nextButton['js'] = array('onclick' => "return submitOnce(this,'{$this->_name}','" . ts('Processing') . "');");
1116 $buttons[] = $nextButton;
1118 $this->addButtons($buttons);
1122 * @param string $name
1123 * @param string $from
1125 * @param string $label
1126 * @param string $dateFormat
1127 * @param bool $required
1128 * @param bool $displayTime
1130 public function addDateRange($name, $from = '_from', $to = '_to', $label = 'From:', $dateFormat = 'searchDate', $required = FALSE, $displayTime = FALSE) {
1132 $this->addDateTime($name . $from, $label, $required, array('formatType' => $dateFormat));
1133 $this->addDateTime($name . $to, ts('To:'), $required, array('formatType' => $dateFormat));
1136 $this->addDate($name . $from, $label, $required, array('formatType' => $dateFormat));
1137 $this->addDate($name . $to, ts('To:'), $required, array('formatType' => $dateFormat));
1142 * Based on form action, return a string representing the api action.
1143 * Used by addField method.
1147 private function getApiAction() {
1148 $action = $this->getAction();
1149 if ($action & (CRM_Core_Action
::UPDATE + CRM_Core_Action
::ADD
)) {
1152 if ($action & (CRM_Core_Action
::BROWSE
)) {
1155 // If you get this exception try adding more cases above.
1156 throw new Exception("Cannot determine api action for " . __CLASS__
);
1160 * Classes extending CRM_Core_Form should implement this method.
1163 public function getDefaultEntity() {
1164 throw new Exception("Cannot determine default entity. The form class should implement getDefaultEntity().");
1168 * Classes extending CRM_Core_Form should implement this method.
1170 * TODO: Merge with CRM_Core_DAO::buildOptionsContext($context) and add validation.
1173 public function getDefaultContext() {
1174 throw new Exception("Cannot determine default context. The form class should implement getDefaultContext().");
1178 * Adds a select based on field metadata.
1179 * TODO: This could be even more generic and widget type (select in this case) could also be read from metadata
1180 * Perhaps a method like $form->bind($name) which would look up all metadata for named field
1182 * Field name to go on the form.
1183 * @param array $props
1184 * Mix of html attributes and special properties, namely.
1185 * - entity (api entity name, can usually be inferred automatically from the form class)
1186 * - field (field name - only needed if different from name used on the form)
1187 * - option_url - path to edit this option list - usually retrieved automatically - set to NULL to disable link
1188 * - placeholder - set to NULL to disable
1190 * - context - @see CRM_Core_DAO::buildOptionsContext
1191 * @param bool $required
1192 * @throws CRM_Core_Exception
1193 * @return HTML_QuickForm_Element
1195 public function addSelect($name, $props = array(), $required = FALSE) {
1196 if (!isset($props['entity'])) {
1197 $props['entity'] = $this->getDefaultEntity();
1199 if (!isset($props['field'])) {
1200 $props['field'] = strrpos($name, '[') ?
rtrim(substr($name, 1 +
strrpos($name, '[')), ']') : $name;
1202 // Fetch options from the api unless passed explicitly
1203 if (isset($props['options'])) {
1204 $options = $props['options'];
1207 $info = civicrm_api3($props['entity'], 'getoptions', $props +
array('check_permissions' => 1));
1208 $options = $info['values'];
1210 if (!array_key_exists('placeholder', $props)) {
1211 $props['placeholder'] = $required ?
ts('- select -') : CRM_Utils_Array
::value('context', $props) == 'search' ?
ts('- any -') : ts('- none -');
1213 // Handle custom field
1214 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
1215 list(, $id) = explode('_', $name);
1216 $label = isset($props['label']) ?
$props['label'] : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', 'label', $id);
1217 $gid = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', 'option_group_id', $id);
1218 if (CRM_Utils_Array
::value('context', $props) != 'search') {
1219 $props['data-option-edit-path'] = array_key_exists('option_url', $props) ?
$props['option_url'] : 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $gid);
1224 $info = civicrm_api3($props['entity'], 'getfields');
1225 foreach ($info['values'] as $uniqueName => $fieldSpec) {
1227 $uniqueName === $props['field'] ||
1228 CRM_Utils_Array
::value('name', $fieldSpec) === $props['field'] ||
1229 in_array($props['field'], CRM_Utils_Array
::value('api.aliases', $fieldSpec, array()))
1234 $label = isset($props['label']) ?
$props['label'] : $fieldSpec['title'];
1235 if (CRM_Utils_Array
::value('context', $props) != 'search') {
1236 $props['data-option-edit-path'] = array_key_exists('option_url', $props) ?
$props['option_url'] : $props['data-option-edit-path'] = CRM_Core_PseudoConstant
::getOptionEditUrl($fieldSpec);
1239 $props['class'] = (isset($props['class']) ?
$props['class'] . ' ' : '') . "crm-select2";
1240 $props['data-api-entity'] = $props['entity'];
1241 $props['data-api-field'] = $props['field'];
1242 CRM_Utils_Array
::remove($props, 'label', 'entity', 'field', 'option_url', 'options', 'context');
1243 return $this->add('select', $name, $label, $options, $required, $props);
1247 * Adds a field based on metadata.
1250 * Field name to go on the form.
1251 * @param array $props
1252 * Mix of html attributes and special properties, namely.
1253 * - entity (api entity name, can usually be inferred automatically from the form class)
1254 * - name (field name - only needed if different from name used on the form)
1255 * - option_url - path to edit this option list - usually retrieved automatically - set to NULL to disable link
1256 * - placeholder - set to NULL to disable
1258 * - context - @see CRM_Core_DAO::buildOptionsContext
1259 * @param bool $required
1260 * @throws \CiviCRM_API3_Exception
1261 * @throws \Exception
1262 * @return HTML_QuickForm_Element
1264 public function addField($name, $props = array(), $required = FALSE) {
1265 // TODO: Handle custom field
1266 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
1267 throw new Exception("Custom fields are not supported by the addField method. ");
1270 if (!isset($props['context'])) {
1271 $props['context'] = $this->getDefaultContext();
1274 if (!isset($props['entity'])) {
1275 $props['entity'] = $this->getDefaultEntity();
1278 if (!isset($props['name'])) {
1279 $props['name'] = strrpos($name, '[') ?
rtrim(substr($name, 1 +
strrpos($name, '[')), ']') : $name;
1282 if (!isset($props['action'])) {
1283 $props['action'] = $this->getApiAction();
1285 // Get field metadata.
1286 $fieldSpec = civicrm_api3($props['entity'], 'getfield', $props);
1287 $fieldSpec = $fieldSpec['values'];
1288 $label = CRM_Utils_Array
::value('label', $props, isset($fieldSpec['title']) ?
$fieldSpec['title'] : NULL);
1290 $widget = isset($props['type']) ?
$props['type'] : $fieldSpec['html']['type'];
1291 if ($widget == 'TextArea' && $props['context'] == 'search') {
1295 $isSelect = (in_array($widget, array(
1298 'Select State/Province',
1299 'Multi-Select State/Province',
1301 'Multi-Select Country',
1309 // Fetch options from the api unless passed explicitly.
1310 if (isset($props['options'])) {
1311 $options = $props['options'];
1312 // Else this get passed to the form->add method.
1313 unset($props['options']);
1316 $options = isset($fieldSpec['options']) ?
$fieldSpec['options'] : NULL;
1318 //@TODO AdvMulti-Select is deprecated, drop support.
1319 if ($props['context'] == 'search' ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
1322 // Set default options-url value.
1323 if ((!isset($props['options-url']))) {
1324 $props['options-url'] = TRUE;
1327 // Add data for popup link.
1328 if ((isset($props['options-url']) && $props['options-url']) && ($props['context'] != 'search' && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM'))) {
1329 $props['data-option-edit-path'] = array_key_exists('option_url', $props) ?
$props['option_url'] : $props['data-option-edit-path'] = CRM_Core_PseudoConstant
::getOptionEditUrl($fieldSpec);
1330 $props['data-api-entity'] = $props['entity'];
1331 $props['data-api-field'] = $props['name'];
1332 if (isset($props['options-url'])) {
1333 unset($props['options-url']);
1337 //Use select2 library for following widgets.
1338 $isSelect2 = (in_array($widget, array(
1341 'Select State/Province',
1342 'Multi-Select State/Province',
1344 'Multi-Select Country',
1347 $props['class'] = (isset($props['class']) ?
$props['class'] . ' ' : '') . "crm-select2";
1348 if ($props['context'] == 'search' ||
strpos($widget, 'Multi') !== FALSE) {
1349 $props['class'] .= ' huge';
1350 $props['multiple'] = 'multiple';
1352 // The placeholder is only used for select-elements.
1353 if (!array_key_exists('placeholder', $props)) {
1354 $props['placeholder'] = $required ?
ts('- select -') : $props['context'] == 'search' ?
ts('- any -') : ts('- none -');
1357 $props +
= CRM_Utils_Array
::value('html', $fieldSpec, array());
1358 CRM_Utils_Array
::remove($props, 'entity', 'name', 'context', 'label', 'action', 'type');
1359 // TODO: refactor switch statement, to separate methods.
1363 //TODO: Autodetect ranges
1364 $props['size'] = isset($props['size']) ?
$props['size'] : 60;
1365 return $this->add('text', $name, $label, $props, $required);
1368 return $this->add('hidden', $name, NULL, $props, $required);
1371 //Set default columns and rows for textarea.
1372 $props['rows'] = isset($props['rows']) ?
$props['rows'] : 4;
1373 $props['cols'] = isset($props['cols']) ?
$props['cols'] : 60;
1374 return $this->addElement('textarea', $name, $label, $props, $required);
1377 //TODO: add range support
1378 //TODO: Add date formats
1379 //TODO: Add javascript template for dates.
1380 return $this->addDate($name, $label, $required, $props);
1383 $separator = isset($props['separator']) ?
$props['separator'] : NULL;
1384 unset($props['separator']);
1385 if (!isset($props['allowClear'])) {
1386 $props['allowClear'] = !$required;
1388 return $this->addRadio($name, $label, $options, $props, $separator, $required);
1391 if (empty($props['multiple'])) {
1392 $options = array('' => $props['placeholder']) +
$options;
1394 // TODO: Add and/or option for fields that store multiple values
1395 return $this->add('select', $name, $label, $options, $required, $props);
1397 case 'CheckBoxGroup':
1398 return $this->addCheckBox($name, $label, array_flip($options), $required, $props);
1401 return $this->addRadio($name, $label, $options, $props, NULL, $required);
1403 //case 'AdvMulti-Select':
1405 $text = isset($props['text']) ?
$props['text'] : NULL;
1406 unset($props['text']);
1407 return $this->addElement('checkbox', $name, $label, $text, $props);
1410 // We should not build upload file in search mode.
1411 if (isset($props['context']) && $props['context'] == 'search') {
1414 $file = $this->add('file', $name, $label, $props, $required);
1415 $this->addUploadElement($name);
1418 //case 'RichTextEditor':
1419 //TODO: Add javascript template for wysiwyg.
1420 case 'Autocomplete-Select':
1422 return $this->addEntityRef($name, $label, $props, $required);
1424 // Check datatypes of fields
1429 //case read only fields
1431 throw new Exception("Unsupported html-element " . $widget);
1436 * Add a widget for selecting/editing/creating/copying a profile form
1438 * @param string $name
1439 * HTML form-element name.
1440 * @param string $label
1442 * @param string $allowCoreTypes
1443 * Only present a UFGroup if its group_type includes a subset of $allowCoreTypes; e.g. 'Individual', 'Activity'.
1444 * @param string $allowSubTypes
1445 * Only present a UFGroup if its group_type is compatible with $allowSubypes.
1446 * @param array $entities
1447 * @param bool $default
1450 public function addProfileSelector($name, $label, $allowCoreTypes, $allowSubTypes, $entities, $default = FALSE) {
1452 // FIXME: Instead of adhoc serialization, use a single json_encode()
1453 CRM_UF_Page_ProfileEditor
::registerProfileScripts();
1454 CRM_UF_Page_ProfileEditor
::registerSchemas(CRM_Utils_Array
::collect('entity_type', $entities));
1455 $this->add('text', $name, $label, array(
1456 'class' => 'crm-profile-selector',
1457 // Note: client treats ';;' as equivalent to \0, and ';;' works better in HTML
1458 'data-group-type' => CRM_Core_BAO_UFGroup
::encodeGroupType($allowCoreTypes, $allowSubTypes, ';;'),
1459 'data-entities' => json_encode($entities),
1461 'data-default' => $default,
1468 * @param null $required
1469 * @param null $extra
1471 public function addCountry($id, $title, $required = NULL, $extra = NULL) {
1472 $this->addElement('select', $id, $title,
1474 '' => ts('- select -'),
1475 ) + CRM_Core_PseudoConstant
::country(), $extra
1478 $this->addRule($id, ts('Please select %1', array(1 => $title)), 'required');
1483 * @param string $name
1486 * @param $attributes
1487 * @param null $required
1488 * @param null $javascriptMethod
1490 public function addSelectOther($name, $label, $options, $attributes, $required = NULL, $javascriptMethod = NULL) {
1492 $this->addElement('select', $name . '_id', $label, $options, $javascriptMethod);
1495 $this->addRule($name . '_id', ts('Please select %1', array(1 => $label)), 'required');
1502 public function getRootTitle() {
1509 public function getCompleteTitle() {
1510 return $this->getRootTitle() . $this->getTitle();
1514 * @return CRM_Core_Smarty
1516 public static function &getTemplate() {
1517 return self
::$_template;
1521 * @param $elementName
1523 public function addUploadElement($elementName) {
1524 $uploadNames = $this->get('uploadNames');
1525 if (!$uploadNames) {
1526 $uploadNames = array();
1528 if (is_array($elementName)) {
1529 foreach ($elementName as $name) {
1530 if (!in_array($name, $uploadNames)) {
1531 $uploadNames[] = $name;
1536 if (!in_array($elementName, $uploadNames)) {
1537 $uploadNames[] = $elementName;
1540 $this->set('uploadNames', $uploadNames);
1542 $config = CRM_Core_Config
::singleton();
1543 if (!empty($uploadNames)) {
1544 $this->controller
->addUploadAction($config->customFileUploadDir
, $uploadNames);
1551 public function buttonType() {
1552 $uploadNames = $this->get('uploadNames');
1553 $buttonType = (is_array($uploadNames) && !empty($uploadNames)) ?
'upload' : 'next';
1554 $this->assign('buttonType', $buttonType);
1563 public function getVar($name) {
1564 return isset($this->$name) ?
$this->$name : NULL;
1571 public function setVar($name, $value) {
1572 $this->$name = $value;
1579 * // if you need time
1580 * $attributes = array(
1581 * 'addTime' => true,
1582 * 'formatType' => 'relative' or 'birth' etc check advanced date settings
1586 * @param string $name
1587 * Name of the element.
1588 * @param string $label
1589 * Label of the element.
1590 * @param bool $required
1592 * @param array $attributes
1595 public function addDate($name, $label, $required = FALSE, $attributes = NULL) {
1596 if (!empty($attributes['formatType'])) {
1597 // get actual format
1598 $params = array('name' => $attributes['formatType']);
1601 // cache date information
1603 $key = "dateFormat_" . str_replace(' ', '_', $attributes['formatType']);
1604 if (empty($dateFormat[$key])) {
1605 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
1606 $dateFormat[$key] = $values;
1609 $values = $dateFormat[$key];
1612 if ($values['date_format']) {
1613 $attributes['format'] = $values['date_format'];
1616 if (!empty($values['time_format'])) {
1617 $attributes['timeFormat'] = $values['time_format'];
1619 $attributes['startOffset'] = $values['start'];
1620 $attributes['endOffset'] = $values['end'];
1623 $config = CRM_Core_Config
::singleton();
1624 if (empty($attributes['format'])) {
1625 $attributes['format'] = $config->dateInputFormat
;
1628 if (!isset($attributes['startOffset'])) {
1629 $attributes['startOffset'] = 10;
1632 if (!isset($attributes['endOffset'])) {
1633 $attributes['endOffset'] = 10;
1636 $this->add('text', $name, $label, $attributes);
1638 if (!empty($attributes['addTime']) ||
!empty($attributes['timeFormat'])) {
1640 if (!isset($attributes['timeFormat'])) {
1641 $timeFormat = $config->timeInputFormat
;
1644 $timeFormat = $attributes['timeFormat'];
1647 // 1 - 12 hours and 2 - 24 hours, but for jquery widget it is 0 and 1 respectively
1649 $show24Hours = TRUE;
1650 if ($timeFormat == 1) {
1651 $show24Hours = FALSE;
1654 //CRM-6664 -we are having time element name
1655 //in either flat string or an array format.
1656 $elementName = $name . '_time';
1657 if (substr($name, -1) == ']') {
1658 $elementName = substr($name, 0, strlen($name) - 1) . '_time]';
1661 $this->add('text', $elementName, ts('Time'), array('timeFormat' => $show24Hours));
1666 $this->addRule($name, ts('Please select %1', array(1 => $label)), 'required');
1667 if (!empty($attributes['addTime']) && !empty($attributes['addTimeRequired'])) {
1668 $this->addRule($elementName, ts('Please enter a time.'), 'required');
1674 * Function that will add date and time.
1676 public function addDateTime($name, $label, $required = FALSE, $attributes = NULL) {
1677 $addTime = array('addTime' => TRUE);
1678 if (is_array($attributes)) {
1679 $attributes = array_merge($attributes, $addTime);
1682 $attributes = $addTime;
1685 $this->addDate($name, $label, $required, $attributes);
1689 * Add a currency and money element to the form.
1691 public function addMoney(
1696 $addCurrency = TRUE,
1697 $currencyName = 'currency',
1698 $defaultCurrency = NULL,
1699 $freezeCurrency = FALSE
1701 $element = $this->add('text', $name, $label, $attributes, $required);
1702 $this->addRule($name, ts('Please enter a valid amount.'), 'money');
1705 $ele = $this->addCurrency($currencyName, NULL, TRUE, $defaultCurrency, $freezeCurrency);
1712 * Add currency element to the form.
1714 public function addCurrency(
1718 $defaultCurrency = NULL,
1719 $freezeCurrency = FALSE
1721 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
1722 $options = array('class' => 'crm-select2 eight');
1724 $currencies = array('' => '') +
$currencies;
1725 $options['placeholder'] = ts('- none -');
1727 $ele = $this->add('select', $name, $label, $currencies, $required, $options);
1728 if ($freezeCurrency) {
1731 if (!$defaultCurrency) {
1732 $config = CRM_Core_Config
::singleton();
1733 $defaultCurrency = $config->defaultCurrency
;
1735 $this->setDefaults(array($name => $defaultCurrency));
1739 * Create a single or multiple entity ref field.
1740 * @param string $name
1741 * @param string $label
1742 * @param array $props
1743 * Mix of html and widget properties, including:.
1744 * - select - params to give to select2 widget
1745 * - entity - defaults to contact
1746 * - create - can the user create a new entity on-the-fly?
1747 * Set to TRUE if entity is contact and you want the default profiles,
1748 * or pass in your own set of links. @see CRM_Core_BAO_UFGroup::getCreateLinks for format
1749 * note that permissions are checked automatically
1750 * - api - array of settings for the getlist api wrapper
1751 * note that it accepts a 'params' setting which will be passed to the underlying api
1752 * - placeholder - string
1754 * - class, etc. - other html properties
1755 * @param bool $required
1757 * @return HTML_QuickForm_Element
1759 public function addEntityRef($name, $label = '', $props = array(), $required = FALSE) {
1760 require_once "api/api.php";
1761 $config = CRM_Core_Config
::singleton();
1762 // Default properties
1763 $props['api'] = CRM_Utils_Array
::value('api', $props, array());
1764 $props['entity'] = _civicrm_api_get_entity_name_from_camel(CRM_Utils_Array
::value('entity', $props, 'contact'));
1765 $props['class'] = ltrim(CRM_Utils_Array
::value('class', $props, '') . ' crm-form-entityref');
1767 if ($props['entity'] == 'contact' && isset($props['create']) && !(CRM_Core_Permission
::check('edit all contacts') || CRM_Core_Permission
::check('add contacts'))) {
1768 unset($props['create']);
1771 $props['placeholder'] = CRM_Utils_Array
::value('placeholder', $props, $required ?
ts('- select %1 -', array(1 => ts(str_replace('_', ' ', $props['entity'])))) : ts('- none -'));
1773 $defaults = array();
1774 if (!empty($props['multiple'])) {
1775 $defaults['multiple'] = TRUE;
1777 $props['select'] = CRM_Utils_Array
::value('select', $props, array()) +
$defaults;
1779 $this->formatReferenceFieldAttributes($props);
1780 return $this->add('text', $name, $label, $props, $required);
1786 private function formatReferenceFieldAttributes(&$props) {
1787 $props['data-select-params'] = json_encode($props['select']);
1788 $props['data-api-params'] = $props['api'] ?
json_encode($props['api']) : NULL;
1789 $props['data-api-entity'] = $props['entity'];
1790 if (!empty($props['create'])) {
1791 $props['data-create-links'] = json_encode($props['create']);
1793 CRM_Utils_Array
::remove($props, 'multiple', 'select', 'api', 'entity', 'create');
1797 * Convert all date fields within the params to mysql date ready for the
1798 * BAO layer. In this case fields are checked against the $_datefields defined for the form
1799 * and if time is defined it is incorporated
1801 * @param array $params
1802 * Input params from the form.
1804 * @todo it would probably be better to work on $this->_params than a passed array
1805 * @todo standardise the format which dates are passed to the BAO layer in & remove date
1808 public function convertDateFieldsToMySQL(&$params) {
1809 foreach ($this->_dateFields
as $fieldName => $specs) {
1810 if (!empty($params[$fieldName])) {
1811 $params[$fieldName] = CRM_Utils_Date
::isoToMysql(
1812 CRM_Utils_Date
::processDate(
1813 $params[$fieldName],
1814 CRM_Utils_Array
::value("{$fieldName}_time", $params), TRUE)
1818 if (isset($specs['default'])) {
1819 $params[$fieldName] = date('YmdHis', strtotime($specs['default']));
1826 * @param $elementName
1828 public function removeFileRequiredRules($elementName) {
1829 $this->_required
= array_diff($this->_required
, array($elementName));
1830 if (isset($this->_rules
[$elementName])) {
1831 foreach ($this->_rules
[$elementName] as $index => $ruleInfo) {
1832 if ($ruleInfo['type'] == 'uploadedfile') {
1833 unset($this->_rules
[$elementName][$index]);
1836 if (empty($this->_rules
[$elementName])) {
1837 unset($this->_rules
[$elementName]);
1843 * Function that can be defined in Form to override or.
1844 * perform specific action on cancel action
1846 public function cancelAction() {
1850 * Helper function to verify that required fields have been filled.
1851 * Typically called within the scope of a FormRule function
1853 public static function validateMandatoryFields($fields, $values, &$errors) {
1854 foreach ($fields as $name => $fld) {
1855 if (!empty($fld['is_required']) && CRM_Utils_System
::isNull(CRM_Utils_Array
::value($name, $values))) {
1856 $errors[$name] = ts('%1 is a required field.', array(1 => $fld['title']));
1862 * Get contact if for a form object. Prioritise
1863 * - cid in URL if 0 (on behalf on someoneelse)
1864 * (@todo consider setting a variable if onbehalf for clarity of downstream 'if's
1865 * - logged in user id if it matches the one in the cid in the URL
1866 * - contact id validated from a checksum from a checksum
1867 * - cid from the url if the caller has ACL permission to view
1868 * - fallback is logged in user (or ? NULL if no logged in user) (@todo wouldn't 0 be more intuitive?)
1872 public function getContactID() {
1873 $tempID = CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
1874 if (isset($this->_params
) && isset($this->_params
['select_contact_id'])) {
1875 $tempID = $this->_params
['select_contact_id'];
1877 if (isset($this->_params
, $this->_params
[0]) && !empty($this->_params
[0]['select_contact_id'])) {
1878 // event form stores as an indexed array, contribution form not so much...
1879 $tempID = $this->_params
[0]['select_contact_id'];
1882 // force to ignore the authenticated user
1883 if ($tempID === '0' ||
$tempID === 0) {
1884 // we set the cid on the form so that this will be retained for the Confirm page
1885 // in the multi-page form & prevent us returning the $userID when this is called
1887 // we don't really need to set it when $tempID is set because the params have that stored
1888 $this->set('cid', 0);
1889 return (int) $tempID;
1892 $userID = $this->getLoggedInUserContactID();
1894 if (!is_null($tempID) && $tempID === $userID) {
1895 return (int) $userID;
1898 //check if this is a checksum authentication
1899 $userChecksum = CRM_Utils_Request
::retrieve('cs', 'String', $this);
1900 if ($userChecksum) {
1901 //check for anonymous user.
1902 $validUser = CRM_Contact_BAO_Contact_Utils
::validChecksum($tempID, $userChecksum);
1907 // check if user has permission, CRM-12062
1908 elseif ($tempID && CRM_Contact_BAO_Contact_Permission
::allow($tempID)) {
1912 return is_numeric($userID) ?
$userID : NULL;
1916 * Get the contact id of the logged in user.
1918 public function getLoggedInUserContactID() {
1919 // check if the user is logged in and has a contact ID
1920 $session = CRM_Core_Session
::singleton();
1921 return $session->get('userID');
1925 * Add autoselector field -if user has permission to view contacts
1926 * If adding this to a form you also need to add to the tpl e.g
1928 * {if !empty($selectable)}
1929 * <div class="crm-summary-row">
1930 * <div class="crm-label">{$form.select_contact.label}</div>
1931 * <div class="crm-content">
1932 * {$form.select_contact.html}
1937 * @param array $profiles
1938 * Ids of profiles that are on the form (to be autofilled).
1939 * @param array $autoCompleteField
1943 * - url (for ajax lookup)
1945 * @todo add data attributes so we can deal with multiple instances on a form
1947 public function addAutoSelector($profiles = array(), $autoCompleteField = array()) {
1948 $autoCompleteField = array_merge(array(
1949 'id_field' => 'select_contact_id',
1950 'placeholder' => ts('Select someone else ...'),
1951 'show_hide' => TRUE,
1952 'api' => array('params' => array('contact_type' => 'Individual')),
1953 ), $autoCompleteField);
1955 if ($this->canUseAjaxContactLookups()) {
1956 $this->assign('selectable', $autoCompleteField['id_field']);
1957 $this->addEntityRef($autoCompleteField['id_field'], NULL, array(
1958 'placeholder' => $autoCompleteField['placeholder'],
1959 'api' => $autoCompleteField['api'],
1962 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/AlternateContactSelector.js', 1, 'html-header')
1964 'form' => array('autocompletes' => $autoCompleteField),
1965 'ids' => array('profile' => $profiles),
1972 public function canUseAjaxContactLookups() {
1973 if (0 < (civicrm_api3('contact', 'getcount', array('check_permissions' => 1))) &&
1974 CRM_Core_Permission
::check(array(array('access AJAX API', 'access CiviCRM')))
1981 * Add the options appropriate to cid = zero - ie. autocomplete
1983 * @todo there is considerable code duplication between the contribution forms & event forms. It is apparent
1984 * that small pieces of duplication are not being refactored into separate functions because their only shared parent
1985 * is this form. Inserting a class FrontEndForm.php between the contribution & event & this class would allow functions like this
1986 * and a dozen other small ones to be refactored into a shared parent with the reduction of much code duplication
1988 * @param $onlinePaymentProcessorEnabled
1990 public function addCIDZeroOptions($onlinePaymentProcessorEnabled) {
1991 $this->assign('nocid', TRUE);
1992 $profiles = array();
1993 if ($this->_values
['custom_pre_id']) {
1994 $profiles[] = $this->_values
['custom_pre_id'];
1996 if ($this->_values
['custom_post_id']) {
1997 $profiles = array_merge($profiles, (array) $this->_values
['custom_post_id']);
1999 if ($onlinePaymentProcessorEnabled) {
2000 $profiles[] = 'billing';
2002 if (!empty($this->_values
)) {
2003 $this->addAutoSelector($profiles);
2008 * Set default values on form for given contact (or no contact defaults)
2010 * @param mixed $profile_id
2011 * (can be id, or profile name).
2012 * @param int $contactID
2016 public function getProfileDefaults($profile_id = 'Billing', $contactID = NULL) {
2018 $defaults = civicrm_api3('profile', 'getsingle', array(
2019 'profile_id' => (array) $profile_id,
2020 'contact_id' => $contactID,
2024 catch (Exception
$e) {
2025 // the try catch block gives us silent failure -not 100% sure this is a good idea
2026 // as silent failures are often worse than noisy ones
2032 * Sets form attribute.
2035 public function preventAjaxSubmit() {
2036 $this->setAttribute('data-no-ajax-submit', 'true');
2040 * Sets form attribute.
2043 public function allowAjaxSubmit() {
2044 $this->removeAttribute('data-no-ajax-submit');
2048 * Sets page title based on entity and action.
2049 * @param string $entityLabel
2051 public function setPageTitle($entityLabel) {
2052 switch ($this->_action
) {
2053 case CRM_Core_Action
::ADD
:
2054 CRM_Utils_System
::setTitle(ts('New %1', array(1 => $entityLabel)));
2057 case CRM_Core_Action
::UPDATE
:
2058 CRM_Utils_System
::setTitle(ts('Edit %1', array(1 => $entityLabel)));
2061 case CRM_Core_Action
::VIEW
:
2062 case CRM_Core_Action
::PREVIEW
:
2063 CRM_Utils_System
::setTitle(ts('View %1', array(1 => $entityLabel)));
2066 case CRM_Core_Action
::DELETE
:
2067 CRM_Utils_System
::setTitle(ts('Delete %1', array(1 => $entityLabel)));
2073 * Create a chain-select target field. All settings are optional; the defaults usually work.
2075 * @param string $elementName
2076 * @param array $settings
2078 * @return HTML_QuickForm_Element
2080 public function addChainSelect($elementName, $settings = array()) {
2081 $props = $settings +
= array(
2082 'control_field' => str_replace(array('state_province', 'StateProvince', 'county', 'County'), array(
2088 'data-callback' => strpos($elementName, 'rovince') ?
'civicrm/ajax/jqState' : 'civicrm/ajax/jqCounty',
2089 'label' => strpos($elementName, 'rovince') ?
ts('State/Province') : ts('County'),
2090 'data-empty-prompt' => strpos($elementName, 'rovince') ?
ts('Choose country first') : ts('Choose state first'),
2091 'data-none-prompt' => ts('- N/A -'),
2092 'multiple' => FALSE,
2093 'required' => FALSE,
2094 'placeholder' => empty($settings['required']) ?
ts('- none -') : ts('- select -'),
2096 CRM_Utils_Array
::remove($props, 'label', 'required', 'control_field');
2097 $props['class'] = (empty($props['class']) ?
'' : "{$props['class']} ") . 'crm-select2';
2098 $props['data-select-prompt'] = $props['placeholder'];
2099 $props['data-name'] = $elementName;
2101 $this->_chainSelectFields
[$settings['control_field']] = $elementName;
2103 // Passing NULL instead of an array of options
2104 // CRM-15225 - normally QF will reject any selected values that are not part of the field's options, but due to a
2105 // quirk in our patched version of HTML_QuickForm_select, this doesn't happen if the options are NULL
2106 // which seems a bit dirty but it allows our dynamically-popuplated select element to function as expected.
2107 return $this->add('select', $elementName, $settings['label'], NULL, $settings['required'], $props);
2111 * Set options and attributes for chain select fields based on the controlling field's value
2113 private function preProcessChainSelectFields() {
2114 foreach ($this->_chainSelectFields
as $control => $target) {
2115 // The 'target' might get missing if extensions do removeElement() in a form hook.
2116 if ($this->elementExists($target)) {
2117 $targetField = $this->getElement($target);
2118 $targetType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ?
'county' : 'stateProvince';
2120 // If the control field is on the form, setup chain-select and dynamically populate options
2121 if ($this->elementExists($control)) {
2122 $controlField = $this->getElement($control);
2123 $controlType = $targetType == 'county' ?
'stateProvince' : 'country';
2125 $targetField->setAttribute('class', $targetField->getAttribute('class') . ' crm-chain-select-target');
2127 $css = (string) $controlField->getAttribute('class');
2128 $controlField->updateAttributes(array(
2129 'class' => ($css ?
"$css " : 'crm-select2 ') . 'crm-chain-select-control',
2130 'data-target' => $target,
2132 $controlValue = $controlField->getValue();
2133 if ($controlValue) {
2134 $options = CRM_Core_BAO_Location
::getChainSelectValues($controlValue, $controlType, TRUE);
2136 $targetField->setAttribute('placeholder', $targetField->getAttribute('data-none-prompt'));
2140 $targetField->setAttribute('placeholder', $targetField->getAttribute('data-empty-prompt'));
2141 $targetField->setAttribute('disabled', 'disabled');
2144 // Control field not present - fall back to loading default options
2146 $options = CRM_Core_PseudoConstant
::$targetType();
2148 if (!$targetField->getAttribute('multiple')) {
2149 $options = array('' => $targetField->getAttribute('placeholder')) +
$options;
2150 $targetField->removeAttribute('placeholder');
2152 $targetField->_options
= array();
2153 $targetField->loadArray($options);
2159 * Validate country / state / county match and suppress unwanted "required" errors
2161 private function validateChainSelectFields() {
2162 foreach ($this->_chainSelectFields
as $control => $target) {
2163 if ($this->elementExists($control) && $this->elementExists($target)) {
2164 $controlValue = (array) $this->getElementValue($control);
2165 $targetField = $this->getElement($target);
2166 $controlType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ?
'stateProvince' : 'country';
2167 $targetValue = array_filter((array) $targetField->getValue());
2168 if ($targetValue ||
$this->getElementError($target)) {
2169 $options = CRM_Core_BAO_Location
::getChainSelectValues($controlValue, $controlType, TRUE);
2171 if (!array_intersect($targetValue, array_keys($options))) {
2172 $this->setElementError($target, $controlType == 'country' ?
ts('State/Province does not match the selected Country') : ts('County does not match the selected State/Province'));
2174 } // Suppress "required" error for field if it has no options
2175 elseif (!$options) {
2176 $this->setElementError($target, NULL);