3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * This is our base form. It is part of the Form/Controller/StateMachine
14 * trifecta. Each form is associated with a specific state in the state
15 * machine. Each form can also operate in various modes
18 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 require_once 'HTML/QuickForm/Page.php';
26 class CRM_Core_Form
extends HTML_QuickForm_Page
{
29 * The state object that this form belongs to
35 * The name of this form
41 * The title of this form
44 protected $_title = NULL;
47 * The default values for the form.
51 public $_defaults = [];
54 * (QUASI-PROTECTED) The options passed into this form
56 * This field should marked `protected` and is not generally
57 * intended for external callers, but some edge-cases do use it.
61 public $_options = NULL;
64 * (QUASI-PROTECTED) The mode of operation for this form
66 * This field should marked `protected` and is not generally
67 * intended for external callers, but some edge-cases do use it.
74 * Monetary fields that may be submitted.
76 * Any fields in this list will be converted to non-localised format
77 * if retrieved by `getSubmittedValue`
81 protected $submittableMoneyFields = [];
84 * Available payment processors.
86 * As part of trying to consolidate various payment pages we store processors here & have functions
87 * at this level to manage them.
90 * An array of payment processor details with objects loaded in the 'object' field.
92 protected $_paymentProcessors;
95 * Available payment processors (IDS).
97 * As part of trying to consolidate various payment pages we store processors here & have functions
98 * at this level to manage them. An alternative would be to have a separate Form that is inherited
99 * by all forms that allow payment processing.
102 * An array of the IDS available on this form.
104 public $_paymentProcessorIDs;
107 * Default or selected processor id.
109 * As part of trying to consolidate various payment pages we store processors here & have functions
110 * at this level to manage them. An alternative would be to have a separate Form that is inherited
111 * by all forms that allow payment processing.
115 protected $_paymentProcessorID;
118 * Is pay later enabled for the form.
120 * As part of trying to consolidate various payment pages we store processors here & have functions
121 * at this level to manage them. An alternative would be to have a separate Form that is inherited
122 * by all forms that allow payment processing.
126 protected $_is_pay_later_enabled;
129 * The renderer used for this form
133 protected $_renderer;
136 * An array to hold a list of datefields on the form
137 * so that they can be converted to ISO in a consistent manner
141 * e.g on a form declare $_dateFields = array(
142 * 'receive_date' => array('default' => 'now'),
144 * then in postProcess call $this->convertDateFieldsToMySQL($formValues)
145 * to have the time field re-incorporated into the field & 'now' set if
146 * no value has been passed in
148 protected $_dateFields = [];
151 * Cache the smarty template for efficiency reasons
153 * @var CRM_Core_Smarty
155 static protected $_template;
158 * Indicate if this form should warn users of unsaved changes
161 protected $unsavedChangesWarn;
164 * What to return to the client if in ajax mode (snippet=json)
168 public $ajaxResponse = [];
171 * Url path used to reach this page
175 public $urlPath = [];
178 * Context of the form being loaded.
189 public $submitOnce = FALSE;
192 * Values submitted by the user.
194 * These values have been checked for injection per
195 * https://pear.php.net/manual/en/package.html.html-quickform.html-quickform.exportvalues.php
196 * and are as submitted.
198 * Once set this array should be treated as read only.
202 protected $exportedValues = [];
207 public function getContext() {
208 return $this->context
;
212 * Set context variable.
214 public function setContext() {
215 $this->context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
219 * @var CRM_Core_Controller
224 * Constants for attributes for various form elements
225 * attempt to standardize on the number of variations that we
226 * use of the below form elements
230 const ATTR_SPACING
= ' ';
233 * All checkboxes are defined with a common prefix. This allows us to
234 * have the same javascript to check / clear all the checkboxes etc
235 * If u have multiple groups of checkboxes, you will need to give them different
236 * ids to avoid potential name collision
240 const CB_PREFIX
= 'mark_x_', CB_PREFIY
= 'mark_y_', CB_PREFIZ
= 'mark_z_', CB_PREFIX_LEN
= 7;
244 * @internal to keep track of chain-select fields
246 private $_chainSelectFields = [];
249 * Extra input types we support via the "add" method
252 public static $html5Types = [
260 * Constructor for the basic form page.
262 * We should not use QuickForm directly. This class provides a lot
263 * of default convenient functions, rules and buttons
265 * @param object $state
266 * State associated with this form.
267 * @param \const|\enum|int $action The mode the form is operating in (None/Create/View/Update/Delete)
268 * @param string $method
269 * The type of http method used (GET/POST).
270 * @param string $name
271 * The name of the form if different from class name.
273 * @return \CRM_Core_Form
275 public function __construct(
277 $action = CRM_Core_Action
::NONE
,
283 $this->_name
= $name;
286 // CRM-15153 - FIXME this name translates to a DOM id and is not always unique!
287 $this->_name
= CRM_Utils_String
::getClassName(CRM_Utils_System
::getClassName($this));
290 parent
::__construct($this->_name
, $method);
292 $this->_state
=& $state;
294 $this->_state
->setName($this->_name
);
296 $this->_action
= (int) $action;
298 $this->registerRules();
300 // let the constructor initialize this, should happen only once
301 if (!isset(self
::$_template)) {
302 self
::$_template = CRM_Core_Smarty
::singleton();
304 // Workaround for CRM-15153 - give each form a reasonably unique css class
305 $this->addClass(CRM_Utils_System
::getClassName($this));
307 $this->assign('snippet', CRM_Utils_Array
::value('snippet', $_GET));
308 $this->setTranslatedFields();
312 * Set translated fields.
314 * This function is called from the class constructor, allowing us to set
315 * fields on the class that can't be set as properties due to need for
316 * translation or other non-input specific handling.
318 protected function setTranslatedFields() {}
321 * Add one or more css classes to the form.
323 * @param string $className
325 public function addClass($className) {
326 $classes = $this->getAttribute('class');
327 $this->setAttribute('class', ($classes ?
"$classes " : '') . $className);
331 * Register all the standard rules that most forms potentially use.
333 public function registerRules() {
363 foreach ($rules as $rule) {
364 $this->registerRule($rule, 'callback', $rule, 'CRM_Utils_Rule');
369 * Simple easy to use wrapper around addElement.
371 * Deal with simple validation rules.
373 * @param string $type
374 * @param string $name
375 * @param string $label
376 * @param array $attributes (options for select elements)
377 * @param bool $required
378 * @param array $extra
379 * (attributes for select elements).
380 * For datepicker elements this is consistent with the data
381 * from CRM_Utils_Date::getDatePickerExtra
383 * @return HTML_QuickForm_Element
384 * Could be an error object
386 * @throws \CRM_Core_Exception
388 public function &add(
389 $type, $name, $label = '',
390 $attributes = NULL, $required = FALSE, $extra = NULL
392 if ($type === 'radio') {
393 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_Form::addRadio');
396 if ($type !== 'static' && $attributes && !is_array($attributes)) {
397 // The $attributes param used to allow for strings and would default to an
398 // empty string. However, now that the variable is heavily manipulated,
399 // we should expect it to always be an array.
400 CRM_Core_Error
::deprecatedWarning('Attributes passed to CRM_Core_Form::add() are not an array.');
402 // Fudge some extra types that quickform doesn't support
404 if ($type == 'wysiwyg' ||
in_array($type, self
::$html5Types)) {
405 $attributes = ($attributes ?
$attributes : []) +
['class' => ''];
406 $attributes['class'] = ltrim($attributes['class'] . " crm-form-$type");
407 if ($type == 'wysiwyg' && isset($attributes['preset'])) {
408 $attributes['data-preset'] = $attributes['preset'];
409 unset($attributes['preset']);
411 $type = $type == 'wysiwyg' ?
'textarea' : 'text';
413 // Like select but accepts rich array data (with nesting, colors, icons, etc) as option list.
414 if ($inputType == 'select2') {
416 $options = $attributes;
417 $attributes = ($extra ?
$extra : []) +
['class' => ''];
418 $attributes['class'] = ltrim($attributes['class'] . " crm-select2 crm-form-select2");
419 $attributes['data-select-params'] = json_encode(['data' => $options, 'multiple' => !empty($attributes['multiple'])]);
420 unset($attributes['multiple']);
424 // @see https://docs.civicrm.org/dev/en/latest/framework/ui/#date-picker
425 if ($type === 'datepicker') {
426 $attributes = $attributes ?
: [];
427 if (!empty($attributes['formatType'])) {
428 $dateAttributes = CRM_Core_SelectValues
::date($attributes['formatType'], NULL, NULL, NULL, 'Input');
429 if (empty($extra['minDate']) && !empty($dateAttributes['minYear'])) {
430 $extra['minDate'] = $dateAttributes['minYear'] . '-01-01';
432 if (empty($extra['maxDate']) && !empty($dateAttributes['minYear'])) {
433 $extra['maxDate'] = $dateAttributes['maxYear'] . '-12-31';
436 // Support minDate/maxDate properties
437 if (isset($extra['minDate'])) {
438 $extra['minDate'] = date('Y-m-d', strtotime($extra['minDate']));
440 if (isset($extra['maxDate'])) {
441 $extra['maxDate'] = date('Y-m-d', strtotime($extra['maxDate']));
444 $attributes['data-crm-datepicker'] = json_encode((array) $extra);
445 if (!empty($attributes['aria-label']) ||
$label) {
446 $attributes['aria-label'] = $attributes['aria-label'] ??
$label;
450 if ($type === 'select' && is_array($extra)) {
451 // Normalize this property
452 if (!empty($extra['multiple'])) {
453 $extra['multiple'] = 'multiple';
456 unset($extra['multiple']);
458 unset($extra['size'], $extra['maxlength']);
459 // Add placeholder option for select
460 if (isset($extra['placeholder'])) {
461 if ($extra['placeholder'] === TRUE) {
462 $extra['placeholder'] = ts('- select %1 -', [1 => $label]);
464 if (($extra['placeholder'] ||
$extra['placeholder'] === '') && empty($extra['multiple']) && is_array($attributes) && !isset($attributes[''])) {
465 $attributes = ['' => $extra['placeholder']] +
$attributes;
469 $optionContext = NULL;
470 if (!empty($extra['option_context'])) {
471 $optionContext = $extra['option_context'];
472 unset($extra['option_context']);
475 $element = $this->addElement($type, $name, CRM_Utils_String
::purifyHTML($label), $attributes, $extra);
476 if (HTML_QuickForm
::isError($element)) {
477 CRM_Core_Error
::statusBounce(HTML_QuickForm
::errorMessage($element));
480 if ($inputType == 'color') {
481 $this->addRule($name, ts('%1 must contain a color value e.g. #ffffff.', [1 => $label]), 'regex', '/#[0-9a-fA-F]{6}/');
485 if ($type == 'file') {
486 $error = $this->addRule($name, ts('%1 is a required field.', [1 => $label]), 'uploadedfile');
489 $error = $this->addRule($name, ts('%1 is a required field.', [1 => $label]), 'required');
491 if (HTML_QuickForm
::isError($error)) {
492 CRM_Core_Error
::statusBounce(HTML_QuickForm
::errorMessage($element));
496 // Add context for the editing of option groups
497 if ($optionContext) {
498 $element->setAttribute('data-option-edit-context', json_encode($optionContext));
507 * This is called before buildForm. Any pre-processing that
508 * needs to be done for buildForm should be done here.
510 * This is a virtual function and should be redefined if needed.
512 public function preProcess() {
516 * Called after the form is validated.
518 * Any processing of form state etc should be done in this function.
519 * Typically all processing associated with a form should be done
520 * here and relevant state should be stored in the session
522 * This is a virtual function and should be redefined if needed
524 public function postProcess() {
528 * Main process wrapper.
530 * Implemented so that we can call all the hook functions.
532 * @param bool $allowAjax
533 * FIXME: This feels kind of hackish, ideally we would take the json-related code from this function.
534 * and bury it deeper down in the controller
536 public function mainProcess($allowAjax = TRUE) {
537 $this->postProcess();
538 $this->postProcessHook();
540 // Respond with JSON if in AJAX context (also support legacy value '6')
541 if ($allowAjax && !empty($_REQUEST['snippet']) && in_array($_REQUEST['snippet'], [
542 CRM_Core_Smarty
::PRINT_JSON
,
545 $this->ajaxResponse
['buttonName'] = str_replace('_qf_' . $this->getAttribute('id') . '_', '', $this->controller
->getButtonName());
546 $this->ajaxResponse
['action'] = $this->_action
;
547 if (isset($this->_id
) ||
isset($this->id
)) {
548 $this->ajaxResponse
['id'] = $this->id ??
$this->_id
;
550 CRM_Core_Page_AJAX
::returnJsonResponse($this->ajaxResponse
);
555 * The postProcess hook is typically called by the framework.
557 * However in a few cases, the form exits or redirects early in which
558 * case it needs to call this function so other modules can do the needful
559 * Calling this function directly should be avoided if possible. In general a
560 * better way is to do setUserContext so the framework does the redirect
562 public function postProcessHook() {
563 CRM_Utils_Hook
::postProcess(get_class($this), $this);
567 * This virtual function is used to build the form.
569 * It replaces the buildForm associated with QuickForm_Page. This allows us to put
570 * preProcess in front of the actual form building routine
572 public function buildQuickForm() {
576 * This virtual function is used to set the default values of various form elements.
579 * reference to the array of default values
581 public function setDefaultValues() {
586 * This is a virtual function that adds group and global rules to the form.
588 * Keeping it distinct from the form to keep code small
589 * and localized in the form building code
591 public function addRules() {
595 * Performs the server side validation.
598 * true if no error found
599 * @throws HTML_QuickForm_Error
601 public function validate() {
602 $error = parent
::validate();
604 $this->validateChainSelectFields();
608 CRM_Utils_Hook
::validateForm(
610 $this->_submitValues
,
616 if (!empty($hookErrors)) {
617 $this->_errors +
= $hookErrors;
620 return (0 == count($this->_errors
));
624 * Core function that builds the form.
626 * We redefine this function here and expect all CRM forms to build their form in the function
629 public function buildForm() {
630 $this->_formBuilt
= TRUE;
634 CRM_Utils_Hook
::preProcess(get_class($this), $this);
636 $this->assign('translatePermission', CRM_Core_Permission
::check('translate CiviCRM'));
639 $this->controller
->_key
&&
640 $this->controller
->_generateQFKey
642 $this->addElement('hidden', 'qfKey', $this->controller
->_key
);
643 $this->assign('qfKey', $this->controller
->_key
);
647 // _generateQFKey suppresses the qfKey generation on form snippets that
648 // are part of other forms, hence we use that to avoid adding entryURL
649 if ($this->controller
->_generateQFKey
&& $this->controller
->_entryURL
) {
650 $this->addElement('hidden', 'entryURL', $this->controller
->_entryURL
);
653 $this->buildQuickForm();
655 $defaults = $this->setDefaultValues();
656 unset($defaults['qfKey']);
658 if (!empty($defaults)) {
659 $this->setDefaults($defaults);
662 // call the form hook
663 // also call the hook function so any modules can set their own custom defaults
664 // the user can do both the form and set default values with this hook
665 CRM_Utils_Hook
::buildForm(get_class($this), $this);
669 //Set html data-attribute to enable warning user of unsaved changes
670 if ($this->unsavedChangesWarn
=== TRUE
671 ||
(!isset($this->unsavedChangesWarn
)
672 && ($this->_action
& CRM_Core_Action
::ADD ||
$this->_action
& CRM_Core_Action
::UPDATE
)
675 $this->setAttribute('data-warn-changes', 'true');
678 if ($this->submitOnce
) {
679 $this->setAttribute('data-submit-once', 'true');
684 * Add default Next / Back buttons.
686 * @param array $params
687 * Array of associative arrays in the order in which the buttons should be
688 * displayed. The associate array has 3 fields: 'type', 'name' and 'isDefault'
689 * The base form class will define a bunch of static arrays for commonly used
692 public function addButtons($params) {
693 $prevnext = $spacing = [];
694 foreach ($params as $button) {
695 if (!empty($button['submitOnce'])) {
696 $this->submitOnce
= TRUE;
699 $attrs = ['class' => 'crm-form-submit'] +
(array) CRM_Utils_Array
::value('js', $button);
701 // A lot of forms use the hacky method of looking at
702 // `$params['button name']` (dating back to them being inputs with a
703 // "value" of the button label) rather than looking at
704 // `$this->controller->getButtonName()`. It makes sense to give buttons a
705 // value by default as a precaution.
708 if (!empty($button['class'])) {
709 $attrs['class'] .= ' ' . $button['class'];
712 if (!empty($button['isDefault'])) {
713 $attrs['class'] .= ' default';
716 if (in_array($button['type'], ['upload', 'next', 'submit', 'done', 'process', 'refresh'])) {
717 $attrs['class'] .= ' validate';
718 $defaultIcon = 'fa-check';
721 $attrs['class'] .= ' cancel';
722 $defaultIcon = $button['type'] == 'back' ?
'fa-chevron-left' : 'fa-times';
725 if ($button['type'] === 'reset') {
726 $attrs['type'] = 'reset';
727 $prevnext[] = $this->createElement('xbutton', 'reset', $button['name'], $attrs);
730 if (!empty($button['subName'])) {
731 if ($button['subName'] == 'new') {
732 $defaultIcon = 'fa-plus-circle';
734 if ($button['subName'] == 'done') {
735 $defaultIcon = 'fa-check-circle';
737 if ($button['subName'] == 'next') {
738 $defaultIcon = 'fa-chevron-right';
742 if (in_array($button['type'], ['next', 'upload', 'done']) && $button['name'] === ts('Save')) {
743 $attrs['accesskey'] = 'S';
745 $buttonContents = CRM_Core_Page
::crmIcon($button['icon'] ??
$defaultIcon) . ' ' . $button['name'];
746 $buttonName = $this->getButtonName($button['type'], CRM_Utils_Array
::value('subName', $button));
747 $attrs['class'] .= " crm-button crm-button-type-{$button['type']} crm-button{$buttonName}";
748 $attrs['type'] = 'submit';
749 $prevnext[] = $this->createElement('xbutton', $buttonName, $buttonContents, $attrs);
751 if (!empty($button['isDefault'])) {
752 $this->setDefaultAction($button['type']);
755 // if button type is upload, set the enctype
756 if ($button['type'] == 'upload') {
757 $this->updateAttributes(['enctype' => 'multipart/form-data']);
758 $this->setMaxFileSize();
761 // hack - addGroup uses an array to express variable spacing, read from the last element
762 $spacing[] = CRM_Utils_Array
::value('spacing', $button, self
::ATTR_SPACING
);
764 $this->addGroup($prevnext, 'buttons', '', $spacing, FALSE);
768 * Getter function for Name.
772 public function getName() {
777 * Getter function for State.
781 public function &getState() {
782 return $this->_state
;
786 * Getter function for StateType.
790 public function getStateType() {
791 return $this->_state
->getType();
795 * Getter function for title.
797 * Should be over-ridden by derived class.
801 public function getTitle() {
802 return $this->_title ?
$this->_title
: ts('ERROR: Title is not Set');
806 * Setter function for title.
808 * @param string $title
809 * The title of the form.
811 public function setTitle($title) {
812 $this->_title
= $title;
813 CRM_Utils_System
::setTitle($title);
817 * Assign billing type id to bltID.
819 * @throws CRM_Core_Exception
821 public function assignBillingType() {
822 $this->_bltID
= CRM_Core_BAO_LocationType
::getBilling();
823 $this->set('bltID', $this->_bltID
);
824 $this->assign('bltID', $this->_bltID
);
830 public function getPaymentProcessorID(): int {
831 return (int) $this->_paymentProcessorID
;
835 * This if a front end form function for setting the payment processor.
837 * It would be good to sync it with the back-end function on abstractEditPayment & use one everywhere.
839 * @param bool $isPayLaterEnabled
841 * @throws \CRM_Core_Exception
843 protected function assignPaymentProcessor($isPayLaterEnabled) {
844 $this->_paymentProcessors
= CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors([ucfirst($this->_mode
) . 'Mode'], $this->_paymentProcessorIDs
);
845 if ($isPayLaterEnabled) {
846 $this->_paymentProcessors
[0] = CRM_Financial_BAO_PaymentProcessor
::getPayment(0);
849 if (!empty($this->_paymentProcessors
)) {
850 foreach ($this->_paymentProcessors
as $paymentProcessorID => $paymentProcessorDetail) {
851 if (empty($this->_paymentProcessor
) && $paymentProcessorDetail['is_default'] == 1 ||
(count($this->_paymentProcessors
) == 1)
853 $this->_paymentProcessor
= $paymentProcessorDetail;
854 $this->assign('paymentProcessor', $this->_paymentProcessor
);
855 // Setting this is a bit of a legacy overhang.
856 $this->_paymentObject
= $paymentProcessorDetail['object'];
859 // It's not clear why we set this on the form.
860 $this->set('paymentProcessors', $this->_paymentProcessors
);
865 * Assign an array of variables to the form/tpl
867 * @param array $values Array of [key => value] to assign to the form
868 * @param array $keys Array of keys to assign from the values array
870 public function assignVariables($values, $keys) {
871 foreach ($keys as $key) {
872 $this->assign($key, $values[$key] ??
NULL);
877 * Format the fields in $this->_params for the payment processor.
879 * In order to pass fields to the payment processor in a consistent way we add some renamed
882 * @param array $fields
886 protected function formatParamsForPaymentProcessor($fields) {
887 $this->_params
= $this->prepareParamsForPaymentProcessor($this->_params
);
888 $fields = array_merge($fields, ['first_name' => 1, 'middle_name' => 1, 'last_name' => 1]);
893 * Format the fields in $params for the payment processor.
895 * In order to pass fields to the payment processor in a consistent way we add some renamed
898 * @param array $params Payment processor params
900 * @return array $params
902 protected function prepareParamsForPaymentProcessor($params) {
903 // also add location name to the array
904 $params["address_name-{$this->_bltID}"] = CRM_Utils_Array
::value('billing_first_name', $params) . ' ' . CRM_Utils_Array
::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array
::value('billing_last_name', $params);
905 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
906 // Add additional parameters that the payment processors are used to receiving.
907 if (!empty($params["billing_state_province_id-{$this->_bltID}"])) {
908 $params['state_province'] = $params["state_province-{$this->_bltID}"] = $params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($params["billing_state_province_id-{$this->_bltID}"]);
910 if (!empty($params["billing_country_id-{$this->_bltID}"])) {
911 $params['country'] = $params["country-{$this->_bltID}"] = $params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($params["billing_country_id-{$this->_bltID}"]);
914 list($hasAddressField, $addressParams) = CRM_Contribute_BAO_Contribution
::getPaymentProcessorReadyAddressParams($params, $this->_bltID
);
915 if ($hasAddressField) {
916 $params = array_merge($params, $addressParams);
919 // How does this relate to similar code in CRM_Contact_BAO_Contact::addBillingNameFieldsIfOtherwiseNotSet()?
920 $nameFields = ['first_name', 'middle_name', 'last_name'];
921 foreach ($nameFields as $name) {
922 if (array_key_exists("billing_$name", $params)) {
923 $params[$name] = $params["billing_{$name}"];
924 $params['preserveDBName'] = TRUE;
928 // For legacy reasons we set these creditcard expiry fields if present
929 CRM_Contribute_Form_AbstractEditPayment
::formatCreditCardDetails($params);
931 // Assign IP address parameter
932 $params['ip_address'] = CRM_Utils_System
::ipAddress();
938 * Handle Payment Processor switching for contribution and event registration forms.
940 * This function is shared between contribution & event forms & this is their common class.
942 * However, this should be seen as an in-progress refactor, the end goal being to also align the
943 * backoffice forms that action payments.
945 * This function overlaps assignPaymentProcessor, in a bad way.
947 protected function preProcessPaymentOptions() {
948 $this->_paymentProcessorID
= NULL;
949 if ($this->_paymentProcessors
) {
950 if (!empty($this->_submitValues
)) {
951 $this->_paymentProcessorID
= $this->_submitValues
['payment_processor_id'] ??
NULL;
952 $this->_paymentProcessor
= $this->_paymentProcessors
[$this->_paymentProcessorID
] ??
NULL;
953 $this->set('type', $this->_paymentProcessorID
);
954 $this->set('mode', $this->_mode
);
955 $this->set('paymentProcessor', $this->_paymentProcessor
);
957 // Set default payment processor
959 foreach ($this->_paymentProcessors
as $values) {
960 if (!empty($values['is_default']) ||
count($this->_paymentProcessors
) == 1) {
961 $this->_paymentProcessorID
= $values['id'];
966 if ($this->_paymentProcessorID
967 ||
(isset($this->_submitValues
['payment_processor_id']) && $this->_submitValues
['payment_processor_id'] == 0)
969 CRM_Core_Payment_ProcessorForm
::preProcess($this);
972 $this->_paymentProcessor
= [];
976 // We save the fact that the profile 'billing' is required on the payment form.
977 // Currently pay-later is the only 'processor' that takes notice of this - but ideally
978 // 1) it would be possible to select the minimum_billing_profile_id for the contribution form
979 // 2) that profile_id would be set on the payment processor
980 // 3) the payment processor would return a billing form that combines these user-configured
981 // minimums with the payment processor minimums. This would lead to fields like 'postal_code'
982 // only being on the form if either the admin has configured it as wanted or the processor
984 $this->assign('billing_profile_id', (!empty($this->_values
['is_billing_required']) ?
'billing' : ''));
988 * Handle pre approval for processors.
990 * This fits with the flow where a pre-approval is done and then confirmed in the next stage when confirm is hit.
992 * This function is shared between contribution & event forms & this is their common class.
994 * However, this should be seen as an in-progress refactor, the end goal being to also align the
995 * backoffice forms that action payments.
997 * @param array $params
999 protected function handlePreApproval(&$params) {
1001 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1002 $params['component'] = $params['component'] ??
'contribute';
1003 $result = $payment->doPreApproval($params);
1004 if (empty($result)) {
1005 // This could happen, for example, when paypal looks at the button value & decides it is not paypal express.
1009 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
1010 CRM_Core_Error
::statusBounce(ts('Payment approval failed with message :') . $e->getMessage(), $payment->getCancelUrl($params['qfKey'], CRM_Utils_Array
::value('participant_id', $params)));
1013 $this->set('pre_approval_parameters', $result['pre_approval_parameters']);
1014 if (!empty($result['redirect_url'])) {
1015 CRM_Utils_System
::redirect($result['redirect_url']);
1020 * Setter function for options.
1022 * @param mixed $options
1024 public function setOptions($options) {
1025 $this->_options
= $options;
1029 * Render form and return contents.
1033 public function toSmarty() {
1034 $this->preProcessChainSelectFields();
1035 $renderer = $this->getRenderer();
1036 $this->accept($renderer);
1037 $content = $renderer->toArray();
1038 $content['formName'] = $this->getName();
1040 $content['formClass'] = CRM_Utils_System
::getClassName($this);
1045 * Getter function for renderer.
1047 * If renderer is not set create one and initialize it.
1051 public function &getRenderer() {
1052 if (!isset($this->_renderer
)) {
1053 $this->_renderer
= CRM_Core_Form_Renderer
::singleton();
1055 return $this->_renderer
;
1059 * Use the form name to create the tpl file name.
1063 public function getTemplateFileName() {
1064 $ext = CRM_Extension_System
::singleton()->getMapper();
1065 if ($ext->isExtensionClass(CRM_Utils_System
::getClassName($this))) {
1066 $filename = $ext->getTemplateName(CRM_Utils_System
::getClassName($this));
1067 $tplname = $ext->getTemplatePath(CRM_Utils_System
::getClassName($this)) . DIRECTORY_SEPARATOR
. $filename;
1071 CRM_Utils_System
::getClassName($this),
1073 '_' => DIRECTORY_SEPARATOR
,
1074 '\\' => DIRECTORY_SEPARATOR
,
1082 * A wrapper for getTemplateFileName.
1084 * This includes calling the hook to prevent us from having to copy & paste the logic of calling the hook.
1086 public function getHookedTemplateFileName() {
1087 $pageTemplateFile = $this->getTemplateFileName();
1088 CRM_Utils_Hook
::alterTemplateFile(get_class($this), $this, 'page', $pageTemplateFile);
1089 return $pageTemplateFile;
1093 * Default extra tpl file basically just replaces .tpl with .extra.tpl.
1095 * i.e. we do not override.
1099 public function overrideExtraTemplateFileName() {
1104 * Error reporting mechanism.
1106 * @param string $message
1110 * @param CRM_Core_DAO $dao
1111 * A data access object on which we perform a rollback if non - empty.
1113 public function error($message, $code = NULL, $dao = NULL) {
1115 $dao->query('ROLLBACK');
1118 $error = CRM_Core_Error
::singleton();
1120 $error->push($code, $message);
1124 * Store the variable with the value in the form scope.
1126 * @param string $name
1127 * Name of the variable.
1128 * @param mixed $value
1129 * Value of the variable.
1131 public function set($name, $value) {
1132 $this->controller
->set($name, $value);
1136 * Get the variable from the form scope.
1138 * @param string $name
1139 * Name of the variable
1143 public function get($name) {
1144 return $this->controller
->get($name);
1148 * Getter for action.
1152 public function getAction() {
1153 return $this->_action
;
1157 * Setter for action.
1159 * @param int $action
1160 * The mode we want to set the form.
1162 public function setAction($action) {
1163 $this->_action
= $action;
1167 * Assign value to name in template.
1169 * @param string $var
1171 * @param mixed $value
1172 * Value of variable.
1174 public function assign($var, $value = NULL) {
1175 self
::$_template->assign($var, $value);
1179 * Assign value to name in template by reference.
1181 * @param string $var
1183 * @param mixed $value
1184 * Value of variable.
1186 public function assign_by_ref($var, &$value) {
1187 self
::$_template->assign_by_ref($var, $value);
1191 * Appends values to template variables.
1193 * @param array|string $tpl_var the template variable name(s)
1194 * @param mixed $value
1195 * The value to append.
1196 * @param bool $merge
1198 public function append($tpl_var, $value = NULL, $merge = FALSE) {
1199 self
::$_template->append($tpl_var, $value, $merge);
1203 * Returns an array containing template variables.
1205 * @param string $name
1209 public function get_template_vars($name = NULL) {
1210 return self
::$_template->get_template_vars($name);
1214 * @param string $name
1217 * @param array $attributes
1218 * @param null $separator
1219 * @param bool $required
1220 * @param array $optionAttributes - Option specific attributes
1222 * @return HTML_QuickForm_group
1224 public function &addRadio($name, $title, $values, $attributes = [], $separator = NULL, $required = FALSE, $optionAttributes = []) {
1226 $attributes = $attributes ?
$attributes : [];
1227 $allowClear = !empty($attributes['allowClear']);
1228 unset($attributes['allowClear']);
1229 $attributes['id_suffix'] = $name;
1230 foreach ($values as $key => $var) {
1231 $optAttributes = $attributes;
1232 if (!empty($optionAttributes[$key])) {
1233 foreach ($optionAttributes[$key] as $optAttr => $optVal) {
1234 $optAttributes[$optAttr] = ltrim(($optAttributes[$optAttr] ??
'') . ' ' . $optVal);
1237 // We use a class here to avoid html5 issues with collapsed cutsomfield sets.
1238 $optAttributes['class'] = $optAttributes['class'] ??
'';
1240 $optAttributes['class'] .= ' required';
1242 $element = $this->createElement('radio', NULL, NULL, $var, $key, $optAttributes);
1243 $options[] = $element;
1245 $group = $this->addGroup($options, $name, $title, $separator);
1247 $optionEditKey = 'data-option-edit-path';
1248 if (!empty($attributes[$optionEditKey])) {
1249 $group->setAttribute($optionEditKey, $attributes[$optionEditKey]);
1253 $this->addRule($name, ts('%1 is a required field.', [1 => $title]), 'required');
1256 $group->setAttribute('allowClear', TRUE);
1264 * @param bool $allowClear
1265 * @param null $required
1266 * @param array $attributes
1268 public function addYesNo($id, $title, $allowClear = FALSE, $required = NULL, $attributes = []) {
1269 $attributes +
= ['id_suffix' => $id];
1271 $choice[] = $this->createElement('radio', NULL, '11', ts('Yes'), '1', $attributes);
1272 $choice[] = $this->createElement('radio', NULL, '11', ts('No'), '0', $attributes);
1274 $group = $this->addGroup($choice, $id, $title);
1276 $group->setAttribute('allowClear', TRUE);
1279 $this->addRule($id, ts('%1 is a required field.', [1 => $title]), 'required');
1287 * @param null $other
1288 * @param null $attributes
1289 * @param null $required
1290 * @param null $javascriptMethod
1291 * @param string $separator
1292 * @param bool $flipValues
1294 public function addCheckBox(
1295 $id, $title, $values, $other = NULL,
1296 $attributes = NULL, $required = NULL,
1297 $javascriptMethod = NULL,
1298 $separator = '<br />', $flipValues = FALSE
1302 if ($javascriptMethod) {
1303 foreach ($values as $key => $var) {
1305 $options[] = $this->createElement('checkbox', $var, NULL, $key, $javascriptMethod, $attributes);
1308 $options[] = $this->createElement('checkbox', $key, NULL, $var, $javascriptMethod, $attributes);
1313 foreach ($values as $key => $var) {
1315 $options[] = $this->createElement('checkbox', $var, NULL, $key, $attributes);
1318 $options[] = $this->createElement('checkbox', $key, NULL, $var, $attributes);
1323 $group = $this->addGroup($options, $id, $title, $separator);
1324 $optionEditKey = 'data-option-edit-path';
1325 if (!empty($attributes[$optionEditKey])) {
1326 $group->setAttribute($optionEditKey, $attributes[$optionEditKey]);
1330 $this->addElement('text', $id . '_other', ts('Other'), $attributes[$id . '_other']);
1335 ts('%1 is a required field.', [1 => $title]),
1341 public function resetValues() {
1342 $data = $this->controller
->container();
1343 $data['values'][$this->_name
] = [];
1347 * Simple shell that derived classes can call to add buttons to
1348 * the form with a customized title for the main Submit
1350 * @param string $title
1351 * Title of the main button.
1352 * @param string $nextType
1353 * Button type for the form after processing.
1354 * @param string $backType
1355 * @param bool|string $submitOnce
1357 public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
1359 if ($backType != NULL) {
1361 'type' => $backType,
1362 'name' => ts('Previous'),
1365 if ($nextType != NULL) {
1367 'type' => $nextType,
1369 'isDefault' => TRUE,
1372 $this->submitOnce
= TRUE;
1374 $buttons[] = $nextButton;
1376 $this->addButtons($buttons);
1380 * @param string $name
1381 * @param string $from
1383 * @param string $label
1384 * @param string $dateFormat
1385 * @param bool $required
1386 * @param bool $displayTime
1388 public function addDateRange($name, $from = '_from', $to = '_to', $label = 'From:', $dateFormat = 'searchDate', $required = FALSE, $displayTime = FALSE) {
1389 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Core_Form::addDatePickerRange insted');
1391 $this->addDateTime($name . $from, $label, $required, ['formatType' => $dateFormat]);
1392 $this->addDateTime($name . $to, ts('To:'), $required, ['formatType' => $dateFormat]);
1395 $this->addDate($name . $from, $label, $required, ['formatType' => $dateFormat]);
1396 $this->addDate($name . $to, ts('To:'), $required, ['formatType' => $dateFormat]);
1401 * Add a search for a range using date picker fields.
1403 * @param string $fieldName
1404 * @param string $label
1405 * @param bool $isDateTime
1406 * Is this a date-time field (not just date).
1407 * @param bool $required
1408 * @param string $fromLabel
1409 * @param string $toLabel
1410 * @param array $additionalOptions
1411 * @param string $to string to append to the to field.
1412 * @param string $from string to append to the from field.
1414 public function addDatePickerRange($fieldName, $label, $isDateTime = FALSE, $required = FALSE, $fromLabel = 'From', $toLabel = 'To', $additionalOptions = [],
1415 $to = '_high', $from = '_low') {
1418 '' => ts('- any -'),
1419 0 => ts('Choose Date Range'),
1420 ] + CRM_Core_OptionGroup
::values('relative_date_filters');
1422 if ($additionalOptions) {
1423 foreach ($additionalOptions as $key => $optionLabel) {
1424 $options[$key] = $optionLabel;
1428 $this->add('select',
1429 "{$fieldName}_relative",
1433 ['class' => 'crm-select2']
1435 $attributes = ['formatType' => 'searchDate'];
1436 $extra = ['time' => $isDateTime];
1437 $this->add('datepicker', $fieldName . $from, ts($fromLabel), $attributes, $required, $extra);
1438 $this->add('datepicker', $fieldName . $to, ts($toLabel), $attributes, $required, $extra);
1442 * Based on form action, return a string representing the api action.
1443 * Used by addField method.
1447 protected function getApiAction() {
1448 $action = $this->getAction();
1449 if ($action & (CRM_Core_Action
::UPDATE + CRM_Core_Action
::ADD
)) {
1452 if ($action & (CRM_Core_Action
::VIEW + CRM_Core_Action
::BROWSE + CRM_Core_Action
::BASIC + CRM_Core_Action
::ADVANCED + CRM_Core_Action
::PREVIEW
)) {
1455 if ($action & (CRM_Core_Action
::DELETE
)) {
1458 // If you get this exception try adding more cases above.
1459 throw new Exception("Cannot determine api action for " . get_class($this) . '.' . 'CRM_Core_Action "' . CRM_Core_Action
::description($action) . '" not recognized.');
1463 * Classes extending CRM_Core_Form should implement this method.
1466 public function getDefaultEntity() {
1467 throw new Exception("Cannot determine default entity. " . get_class($this) . " should implement getDefaultEntity().");
1471 * Classes extending CRM_Core_Form should implement this method.
1473 * TODO: Merge with CRM_Core_DAO::buildOptionsContext($context) and add validation.
1476 public function getDefaultContext() {
1477 throw new Exception("Cannot determine default context. " . get_class($this) . " should implement getDefaultContext().");
1481 * Adds a select based on field metadata.
1482 * TODO: This could be even more generic and widget type (select in this case) could also be read from metadata
1483 * Perhaps a method like $form->bind($name) which would look up all metadata for named field
1485 * Field name to go on the form.
1486 * @param array $props
1487 * Mix of html attributes and special properties, namely.
1488 * - entity (api entity name, can usually be inferred automatically from the form class)
1489 * - field (field name - only needed if different from name used on the form)
1490 * - option_url - path to edit this option list - usually retrieved automatically - set to NULL to disable link
1491 * - placeholder - set to NULL to disable
1493 * - context - @see CRM_Core_DAO::buildOptionsContext
1494 * @param bool $required
1495 * @throws CRM_Core_Exception
1496 * @return HTML_QuickForm_Element
1498 public function addSelect($name, $props = [], $required = FALSE) {
1499 if (!isset($props['entity'])) {
1500 $props['entity'] = $this->getDefaultEntity();
1502 if (!isset($props['field'])) {
1503 $props['field'] = strrpos($name, '[') ?
rtrim(substr($name, 1 +
strrpos($name, '[')), ']') : $name;
1505 if (!isset($props['context'])) {
1507 $props['context'] = $this->getDefaultContext();
1509 // This is not a required param, so we'll ignore if this doesn't exist.
1510 catch (Exception
$e) {
1513 // Fetch options from the api unless passed explicitly
1514 if (isset($props['options'])) {
1515 $options = $props['options'];
1518 $info = civicrm_api3($props['entity'], 'getoptions', $props);
1519 $options = $info['values'];
1521 if (!array_key_exists('placeholder', $props) && $placeholder = self
::selectOrAnyPlaceholder($props, $required)) {
1522 $props['placeholder'] = $placeholder;
1524 // Handle custom field
1525 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
1526 list(, $id) = explode('_', $name);
1527 $label = $props['label'] ?? CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', 'label', $id);
1528 $gid = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', 'option_group_id', $id);
1529 if (CRM_Utils_Array
::value('context', $props) != 'search') {
1530 $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);
1535 $info = civicrm_api3($props['entity'], 'getfields');
1536 foreach ($info['values'] as $uniqueName => $fieldSpec) {
1538 $uniqueName === $props['field'] ||
1539 CRM_Utils_Array
::value('name', $fieldSpec) === $props['field'] ||
1540 in_array($props['field'], CRM_Utils_Array
::value('api.aliases', $fieldSpec, []))
1545 $label = $props['label'] ??
$fieldSpec['title'];
1546 if (CRM_Utils_Array
::value('context', $props) != 'search') {
1547 $props['data-option-edit-path'] = array_key_exists('option_url', $props) ?
$props['option_url'] : CRM_Core_PseudoConstant
::getOptionEditUrl($fieldSpec);
1550 $props['class'] = (isset($props['class']) ?
$props['class'] . ' ' : '') . "crm-select2";
1551 $props['data-api-entity'] = $props['entity'];
1552 $props['data-api-field'] = $props['field'];
1553 CRM_Utils_Array
::remove($props, 'label', 'entity', 'field', 'option_url', 'options', 'context');
1554 return $this->add('select', $name, $label, $options, $required, $props);
1558 * Handles a repeated bit supplying a placeholder for entity selection
1560 * @param string $props
1561 * The field properties, including the entity and context.
1562 * @param bool $required
1563 * If the field is required.
1564 * @param string $title
1565 * A field title, if applicable.
1567 * The placeholder text.
1569 private static function selectOrAnyPlaceholder($props, $required, $title = NULL) {
1570 if (empty($props['entity'])) {
1574 $daoToClass = CRM_Core_DAO_AllCoreTables
::daoToClass();
1575 if (array_key_exists($props['entity'], $daoToClass)) {
1576 $daoClass = $daoToClass[$props['entity']];
1577 $title = $daoClass::getEntityTitle();
1580 $title = ts('option');
1583 if (($props['context'] ??
'') == 'search' && !$required) {
1584 return ts('- any %1 -', [1 => $title]);
1586 return ts('- select %1 -', [1 => $title]);
1590 * Adds a field based on metadata.
1593 * Field name to go on the form.
1594 * @param array $props
1595 * Mix of html attributes and special properties, namely.
1596 * - entity (api entity name, can usually be inferred automatically from the form class)
1597 * - name (field name - only needed if different from name used on the form)
1598 * - option_url - path to edit this option list - usually retrieved automatically - set to NULL to disable link
1599 * - placeholder - set to NULL to disable
1601 * - context - @see CRM_Core_DAO::buildOptionsContext
1602 * @param bool $required
1603 * @param bool $legacyDate
1604 * Temporary param to facilitate the conversion of fields to use the datepicker in
1605 * a controlled way. To convert the field the jcalendar code needs to be removed from the
1606 * tpl as well. That file is intended to be EOL.
1608 * @throws \CiviCRM_API3_Exception
1609 * @throws \Exception
1611 * HTML_QuickForm_Element
1614 public function addField($name, $props = [], $required = FALSE, $legacyDate = TRUE) {
1616 if (empty($props['context'])) {
1617 $props['context'] = $this->getDefaultContext();
1619 $context = $props['context'];
1621 if (empty($props['entity'])) {
1622 $props['entity'] = $this->getDefaultEntity();
1625 if (empty($props['name'])) {
1626 $props['name'] = strrpos($name, '[') ?
rtrim(substr($name, 1 +
strrpos($name, '[')), ']') : $name;
1629 if (empty($props['action'])) {
1630 $props['action'] = $this->getApiAction();
1633 // Handle custom fields
1634 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
1635 $fieldId = (int) substr($name, 7);
1636 return CRM_Core_BAO_CustomField
::addQuickFormElement($this, $name, $fieldId, $required, $context == 'search', CRM_Utils_Array
::value('label', $props));
1639 // Core field - get metadata.
1640 $fieldSpec = civicrm_api3($props['entity'], 'getfield', $props);
1641 $fieldSpec = $fieldSpec['values'];
1642 $fieldSpecLabel = $fieldSpec['html']['label'] ?? CRM_Utils_Array
::value('title', $fieldSpec);
1643 $label = CRM_Utils_Array
::value('label', $props, $fieldSpecLabel);
1645 $widget = $props['type'] ??
$fieldSpec['html']['type'];
1646 if ($widget == 'TextArea' && $context == 'search') {
1650 $isSelect = (in_array($widget, [
1659 // Fetch options from the api unless passed explicitly.
1660 if (isset($props['options'])) {
1661 $options = $props['options'];
1664 $options = $fieldSpec['options'] ??
NULL;
1666 if ($context == 'search') {
1667 $widget = $widget == 'Select2' ?
$widget : 'Select';
1668 $props['multiple'] = CRM_Utils_Array
::value('multiple', $props, TRUE);
1671 // Add data for popup link.
1672 $canEditOptions = CRM_Core_Permission
::check('administer CiviCRM');
1673 $hasOptionUrl = !empty($props['option_url']);
1674 $optionUrlKeyIsSet = array_key_exists('option_url', $props);
1675 $shouldAdd = $context !== 'search' && $isSelect && $canEditOptions;
1677 // Only add if key is not set, or if non-empty option url is provided
1678 if (($hasOptionUrl ||
!$optionUrlKeyIsSet) && $shouldAdd) {
1679 $optionUrl = $hasOptionUrl ?
$props['option_url'] :
1680 CRM_Core_PseudoConstant
::getOptionEditUrl($fieldSpec);
1681 $props['data-option-edit-path'] = $optionUrl;
1682 $props['data-api-entity'] = $props['entity'];
1683 $props['data-api-field'] = $props['name'];
1686 $props +
= CRM_Utils_Array
::value('html', $fieldSpec, []);
1687 if (in_array($widget, ['Select', 'Select2'])
1688 && !array_key_exists('placeholder', $props)
1689 && $placeholder = self
::selectOrAnyPlaceholder($props, $required, $label)) {
1690 $props['placeholder'] = $placeholder;
1692 CRM_Utils_Array
::remove($props, 'entity', 'name', 'context', 'label', 'action', 'type', 'option_url', 'options');
1694 // TODO: refactor switch statement, to separate methods.
1700 //TODO: Autodetect ranges
1701 $props['size'] = $props['size'] ??
60;
1702 return $this->add(strtolower($widget), $name, $label, $props, $required);
1705 return $this->add('hidden', $name, NULL, $props, $required);
1708 //Set default columns and rows for textarea.
1709 $props['rows'] = $props['rows'] ??
4;
1710 $props['cols'] = $props['cols'] ??
60;
1711 if (empty($props['maxlength']) && isset($fieldSpec['length'])) {
1712 $props['maxlength'] = $fieldSpec['length'];
1714 return $this->add('textarea', $name, $label, $props, $required);
1717 // This is a white list for fields that have been tested with
1718 // date picker. We should be able to remove the other
1720 //TODO: add range support
1721 //TODO: Add date formats
1722 //TODO: Add javascript template for dates.
1723 return $this->addDate($name, $label, $required, $props);
1726 $fieldSpec = CRM_Utils_Date
::addDateMetadataToField($fieldSpec, $fieldSpec);
1727 $attributes = ['format' => $fieldSpec['date_format']];
1728 return $this->add('datepicker', $name, $label, $attributes, $required, $fieldSpec['datepicker']['extra']);
1732 $separator = $props['separator'] ??
NULL;
1733 unset($props['separator']);
1734 if (!isset($props['allowClear'])) {
1735 $props['allowClear'] = !$required;
1737 return $this->addRadio($name, $label, $options, $props, $separator, $required);
1741 'required' => $required,
1743 'multiple' => $context == 'search',
1745 return $this->addChainSelect($name, $props);
1749 $props['class'] = CRM_Utils_Array
::value('class', $props, 'big') . ' crm-select2';
1750 // TODO: Add and/or option for fields that store multiple values
1751 return $this->add(strtolower($widget), $name, $label, $options, $required, $props);
1753 case 'CheckBoxGroup':
1754 return $this->addCheckBox($name, $label, array_flip($options), $required, $props);
1757 return $this->addRadio($name, $label, $options, $props, NULL, $required);
1760 if ($context === 'search') {
1761 $this->addYesNo($name, $label, TRUE, FALSE, $props);
1764 $text = $props['text'] ??
NULL;
1765 unset($props['text']);
1766 return $this->addElement('checkbox', $name, $label, $text, $props);
1768 //add support for 'Advcheckbox' field
1770 $text = $props['text'] ??
NULL;
1771 unset($props['text']);
1772 return $this->addElement('advcheckbox', $name, $label, $text, $props);
1775 // We should not build upload file in search mode.
1776 if ($context == 'search') {
1779 $file = $this->add('file', $name, $label, $props, $required);
1780 $this->addUploadElement($name);
1783 case 'RichTextEditor':
1784 return $this->add('wysiwyg', $name, $label, $props, $required);
1787 return $this->addEntityRef($name, $label, $props, $required);
1790 $props['size'] = $props['size'] ??
60;
1791 return $this->add('password', $name, $label, $props, $required);
1793 // Check datatypes of fields
1797 //case read only fields
1799 throw new Exception("Unsupported html-element " . $widget);
1804 * Add a widget for selecting/editing/creating/copying a profile form
1806 * @param string $name
1807 * HTML form-element name.
1808 * @param string $label
1810 * @param string $allowCoreTypes
1811 * Only present a UFGroup if its group_type includes a subset of $allowCoreTypes; e.g. 'Individual', 'Activity'.
1812 * @param string $allowSubTypes
1813 * Only present a UFGroup if its group_type is compatible with $allowSubypes.
1814 * @param array $entities
1815 * @param bool $default
1817 * @param string $usedFor
1819 public function addProfileSelector($name, $label, $allowCoreTypes, $allowSubTypes, $entities, $default = FALSE, $usedFor = NULL) {
1821 // FIXME: Instead of adhoc serialization, use a single json_encode()
1822 CRM_UF_Page_ProfileEditor
::registerProfileScripts();
1823 CRM_UF_Page_ProfileEditor
::registerSchemas(CRM_Utils_Array
::collect('entity_type', $entities));
1824 $this->add('text', $name, $label, [
1825 'class' => 'crm-profile-selector',
1826 // Note: client treats ';;' as equivalent to \0, and ';;' works better in HTML
1827 'data-group-type' => CRM_Core_BAO_UFGroup
::encodeGroupType($allowCoreTypes, $allowSubTypes, ';;'),
1828 'data-entities' => json_encode($entities),
1830 'data-default' => $default,
1831 'data-usedfor' => json_encode($usedFor),
1838 public function getRootTitle() {
1845 public function getCompleteTitle() {
1846 return $this->getRootTitle() . $this->getTitle();
1850 * @return CRM_Core_Smarty
1852 public static function &getTemplate() {
1853 return self
::$_template;
1857 * @param $elementName
1859 public function addUploadElement($elementName) {
1860 $uploadNames = $this->get('uploadNames');
1861 if (!$uploadNames) {
1864 if (is_array($elementName)) {
1865 foreach ($elementName as $name) {
1866 if (!in_array($name, $uploadNames)) {
1867 $uploadNames[] = $name;
1872 if (!in_array($elementName, $uploadNames)) {
1873 $uploadNames[] = $elementName;
1876 $this->set('uploadNames', $uploadNames);
1878 $config = CRM_Core_Config
::singleton();
1879 if (!empty($uploadNames)) {
1880 $this->controller
->addUploadAction($config->customFileUploadDir
, $uploadNames);
1889 public function getVar($name) {
1890 return $this->$name ??
NULL;
1897 public function setVar($name, $value) {
1898 $this->$name = $value;
1905 * Use $this->add('datepicker', ...) instead.
1907 * @param string $name
1908 * Name of the element.
1909 * @param string $label
1910 * Label of the element.
1911 * @param bool $required
1913 * @param array $attributes
1916 public function addDate($name, $label, $required = FALSE, $attributes = NULL) {
1917 if (!empty($attributes['formatType'])) {
1918 // get actual format
1919 $params = ['name' => $attributes['formatType']];
1922 // cache date information
1924 $key = "dateFormat_" . str_replace(' ', '_', $attributes['formatType']);
1925 if (empty($dateFormat[$key])) {
1926 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
1927 $dateFormat[$key] = $values;
1930 $values = $dateFormat[$key];
1933 if ($values['date_format']) {
1934 $attributes['format'] = $values['date_format'];
1937 if (!empty($values['time_format'])) {
1938 $attributes['timeFormat'] = $values['time_format'];
1940 $attributes['startOffset'] = $values['start'];
1941 $attributes['endOffset'] = $values['end'];
1944 $config = CRM_Core_Config
::singleton();
1945 if (empty($attributes['format'])) {
1946 $attributes['format'] = $config->dateInputFormat
;
1949 if (!isset($attributes['startOffset'])) {
1950 $attributes['startOffset'] = 10;
1953 if (!isset($attributes['endOffset'])) {
1954 $attributes['endOffset'] = 10;
1957 $this->add('text', $name, $label, $attributes);
1959 if (!empty($attributes['addTime']) ||
!empty($attributes['timeFormat'])) {
1961 if (!isset($attributes['timeFormat'])) {
1962 $timeFormat = $config->timeInputFormat
;
1965 $timeFormat = $attributes['timeFormat'];
1968 // 1 - 12 hours and 2 - 24 hours, but for jquery widget it is 0 and 1 respectively
1970 $show24Hours = TRUE;
1971 if ($timeFormat == 1) {
1972 $show24Hours = FALSE;
1975 //CRM-6664 -we are having time element name
1976 //in either flat string or an array format.
1977 $elementName = $name . '_time';
1978 if (substr($name, -1) == ']') {
1979 $elementName = substr($name, 0, strlen($name) - 1) . '_time]';
1982 $this->add('text', $elementName, ts('Time'), ['timeFormat' => $show24Hours]);
1987 $this->addRule($name, ts('Please select %1', [1 => $label]), 'required');
1988 if (!empty($attributes['addTime']) && !empty($attributes['addTimeRequired'])) {
1989 $this->addRule($elementName, ts('Please enter a time.'), 'required');
1995 * Function that will add date and time.
1998 * Use $this->add('datepicker', ...) instead.
2000 * @param string $name
2001 * @param string $label
2002 * @param bool $required
2003 * @param null $attributes
2005 public function addDateTime($name, $label, $required = FALSE, $attributes = NULL) {
2006 $addTime = ['addTime' => TRUE];
2007 if (is_array($attributes)) {
2008 $attributes = array_merge($attributes, $addTime);
2011 $attributes = $addTime;
2014 $this->addDate($name, $label, $required, $attributes);
2018 * Add a currency and money element to the form.
2020 * @param string $name
2021 * @param string $label
2022 * @param bool $required
2023 * @param null $attributes
2024 * @param bool $addCurrency
2025 * @param string $currencyName
2026 * @param null $defaultCurrency
2027 * @param bool $freezeCurrency
2029 * @return \HTML_QuickForm_Element
2031 public function addMoney(
2036 $addCurrency = TRUE,
2037 $currencyName = 'currency',
2038 $defaultCurrency = NULL,
2039 $freezeCurrency = FALSE
2041 $element = $this->add('text', $name, $label, $attributes, $required);
2042 $this->addRule($name, ts('Please enter a valid amount.'), 'money');
2045 $ele = $this->addCurrency($currencyName, NULL, TRUE, $defaultCurrency, $freezeCurrency);
2052 * Add currency element to the form.
2054 * @param string $name
2055 * @param null $label
2056 * @param bool $required
2057 * @param string $defaultCurrency
2058 * @param bool $freezeCurrency
2059 * @param bool $setDefaultCurrency
2061 public function addCurrency(
2065 $defaultCurrency = NULL,
2066 $freezeCurrency = FALSE,
2067 $setDefaultCurrency = TRUE
2069 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
2070 if (!empty($defaultCurrency) && !array_key_exists($defaultCurrency, $currencies)) {
2071 Civi
::log()->warning('addCurrency: Currency ' . $defaultCurrency . ' is disabled but still in use!');
2072 $currencies[$defaultCurrency] = $defaultCurrency;
2074 $options = ['class' => 'crm-select2 eight'];
2076 $currencies = ['' => ''] +
$currencies;
2077 $options['placeholder'] = ts('- none -');
2079 $ele = $this->add('select', $name, $label, $currencies, $required, $options);
2080 if ($freezeCurrency) {
2083 if (!$defaultCurrency) {
2084 $config = CRM_Core_Config
::singleton();
2085 $defaultCurrency = $config->defaultCurrency
;
2087 // In some case, setting currency field by default might override the default value
2088 // as encountered in CRM-20527 for batch data entry
2089 if ($setDefaultCurrency) {
2090 $this->setDefaults([$name => $defaultCurrency]);
2095 * Create a single or multiple entity ref field.
2096 * @param string $name
2097 * @param string $label
2098 * @param array $props
2099 * Mix of html and widget properties, including:.
2100 * - select - params to give to select2 widget
2101 * - entity - defaults to Contact
2102 * - create - can the user create a new entity on-the-fly?
2103 * Set to TRUE if entity is contact and you want the default profiles,
2104 * or pass in your own set of links. @see CRM_Campaign_BAO_Campaign::getEntityRefCreateLinks for format
2105 * note that permissions are checked automatically
2106 * - api - array of settings for the getlist api wrapper
2107 * note that it accepts a 'params' setting which will be passed to the underlying api
2108 * - placeholder - string
2110 * - class, etc. - other html properties
2111 * @param bool $required
2113 * @return HTML_QuickForm_Element
2115 public function addEntityRef($name, $label = '', $props = [], $required = FALSE) {
2116 // Default properties
2117 $props['api'] = CRM_Utils_Array
::value('api', $props, []);
2118 $props['entity'] = CRM_Core_DAO_AllCoreTables
::convertEntityNameToCamel($props['entity'] ??
'Contact');
2119 $props['class'] = ltrim(($props['class'] ??
'') . ' crm-form-entityref');
2121 if (array_key_exists('create', $props) && empty($props['create'])) {
2122 unset($props['create']);
2125 $props['placeholder'] = $props['placeholder'] ?? self
::selectOrAnyPlaceholder($props, $required);
2128 if (!empty($props['multiple'])) {
2129 $defaults['multiple'] = TRUE;
2131 $props['select'] = CRM_Utils_Array
::value('select', $props, []) +
$defaults;
2133 $this->formatReferenceFieldAttributes($props, get_class($this));
2134 return $this->add('text', $name, $label, $props, $required);
2138 * @param array $props
2139 * @param string $formName
2141 private function formatReferenceFieldAttributes(&$props, $formName) {
2142 CRM_Utils_Hook
::alterEntityRefParams($props, $formName);
2143 $props['data-select-params'] = json_encode($props['select']);
2144 $props['data-api-params'] = $props['api'] ?
json_encode($props['api']) : NULL;
2145 $props['data-api-entity'] = $props['entity'];
2146 if (!empty($props['create'])) {
2147 $props['data-create-links'] = json_encode($props['create']);
2149 CRM_Utils_Array
::remove($props, 'multiple', 'select', 'api', 'entity', 'create');
2153 * Convert all date fields within the params to mysql date ready for the
2154 * BAO layer. In this case fields are checked against the $_datefields defined for the form
2155 * and if time is defined it is incorporated
2157 * @param array $params
2158 * Input params from the form.
2160 * @todo it would probably be better to work on $this->_params than a passed array
2161 * @todo standardise the format which dates are passed to the BAO layer in & remove date
2164 public function convertDateFieldsToMySQL(&$params) {
2165 foreach ($this->_dateFields
as $fieldName => $specs) {
2166 if (!empty($params[$fieldName])) {
2167 $params[$fieldName] = CRM_Utils_Date
::isoToMysql(
2168 CRM_Utils_Date
::processDate(
2169 $params[$fieldName],
2170 CRM_Utils_Array
::value("{$fieldName}_time", $params), TRUE)
2174 if (isset($specs['default'])) {
2175 $params[$fieldName] = date('YmdHis', strtotime($specs['default']));
2182 * @param $elementName
2184 public function removeFileRequiredRules($elementName) {
2185 $this->_required
= array_diff($this->_required
, [$elementName]);
2186 if (isset($this->_rules
[$elementName])) {
2187 foreach ($this->_rules
[$elementName] as $index => $ruleInfo) {
2188 if ($ruleInfo['type'] == 'uploadedfile') {
2189 unset($this->_rules
[$elementName][$index]);
2192 if (empty($this->_rules
[$elementName])) {
2193 unset($this->_rules
[$elementName]);
2199 * Function that can be defined in Form to override or.
2200 * perform specific action on cancel action
2202 public function cancelAction() {
2206 * Helper function to verify that required fields have been filled.
2208 * Typically called within the scope of a FormRule function
2210 * @param array $fields
2211 * @param array $values
2212 * @param array $errors
2214 public static function validateMandatoryFields($fields, $values, &$errors) {
2215 foreach ($fields as $name => $fld) {
2216 if (!empty($fld['is_required']) && CRM_Utils_System
::isNull(CRM_Utils_Array
::value($name, $values))) {
2217 $errors[$name] = ts('%1 is a required field.', [1 => $fld['title']]);
2223 * Get contact if for a form object. Prioritise
2224 * - cid in URL if 0 (on behalf on someoneelse)
2225 * (@todo consider setting a variable if onbehalf for clarity of downstream 'if's
2226 * - logged in user id if it matches the one in the cid in the URL
2227 * - contact id validated from a checksum from a checksum
2228 * - cid from the url if the caller has ACL permission to view
2229 * - fallback is logged in user (or ? NULL if no logged in user) (@todo wouldn't 0 be more intuitive?)
2233 protected function setContactID() {
2234 $tempID = CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
2235 if (isset($this->_params
) && !empty($this->_params
['select_contact_id'])) {
2236 $tempID = $this->_params
['select_contact_id'];
2238 if (isset($this->_params
, $this->_params
[0]) && !empty($this->_params
[0]['select_contact_id'])) {
2239 // event form stores as an indexed array, contribution form not so much...
2240 $tempID = $this->_params
[0]['select_contact_id'];
2243 // force to ignore the authenticated user
2244 if ($tempID === '0' ||
$tempID === 0) {
2245 // we set the cid on the form so that this will be retained for the Confirm page
2246 // in the multi-page form & prevent us returning the $userID when this is called
2248 // we don't really need to set it when $tempID is set because the params have that stored
2249 $this->set('cid', 0);
2250 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $tempID]);
2251 return (int) $tempID;
2254 $userID = CRM_Core_Session
::getLoggedInContactID();
2256 if (!is_null($tempID) && $tempID === $userID) {
2257 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $tempID]);
2258 return (int) $userID;
2261 //check if this is a checksum authentication
2262 $userChecksum = CRM_Utils_Request
::retrieve('cs', 'String', $this);
2263 if ($userChecksum) {
2264 //check for anonymous user.
2265 $validUser = CRM_Contact_BAO_Contact_Utils
::validChecksum($tempID, $userChecksum);
2267 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $tempID]);
2268 CRM_Core_Resources
::singleton()->addVars('coreForm', ['checksum' => $userChecksum]);
2272 // check if user has permission, CRM-12062
2273 elseif ($tempID && CRM_Contact_BAO_Contact_Permission
::allow($tempID)) {
2274 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $tempID]);
2277 if (is_numeric($userID)) {
2278 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $userID]);
2280 return is_numeric($userID) ?
$userID : NULL;
2284 * Get the contact id that the form is being submitted for.
2288 public function getContactID() {
2289 return $this->setContactID();
2293 * Get the contact id of the logged in user.
2298 public function getLoggedInUserContactID() {
2299 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_Session::getLoggedInContactID()');
2300 // check if the user is logged in and has a contact ID
2301 $session = CRM_Core_Session
::singleton();
2302 return $session->get('userID') ?
(int) $session->get('userID') : FALSE;
2306 * Add autoselector field -if user has permission to view contacts
2307 * If adding this to a form you also need to add to the tpl e.g
2309 * {if !empty($selectable)}
2310 * <div class="crm-summary-row">
2311 * <div class="crm-label">{$form.select_contact.label}</div>
2312 * <div class="crm-content">
2313 * {$form.select_contact.html}
2318 * @param array $profiles
2319 * Ids of profiles that are on the form (to be autofilled).
2320 * @param array $autoCompleteField
2324 * - url (for ajax lookup)
2326 * @throws \CRM_Core_Exception
2327 * @todo add data attributes so we can deal with multiple instances on a form
2329 public function addAutoSelector($profiles = [], $autoCompleteField = []) {
2330 $autoCompleteField = array_merge([
2331 'id_field' => 'select_contact_id',
2332 'placeholder' => ts('Select someone else ...'),
2333 'show_hide' => TRUE,
2334 'api' => ['params' => ['contact_type' => 'Individual']],
2335 ], $autoCompleteField);
2337 if ($this->canUseAjaxContactLookups()) {
2338 $this->assign('selectable', $autoCompleteField['id_field']);
2339 $this->addEntityRef($autoCompleteField['id_field'], NULL, [
2340 'placeholder' => $autoCompleteField['placeholder'],
2341 'api' => $autoCompleteField['api'],
2344 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/AlternateContactSelector.js', 1, 'html-header')
2346 'form' => ['autocompletes' => $autoCompleteField],
2347 'ids' => ['profile' => $profiles],
2354 public function canUseAjaxContactLookups() {
2355 if (0 < (civicrm_api3('contact', 'getcount', ['check_permissions' => 1])) &&
2356 CRM_Core_Permission
::check([['access AJAX API', 'access CiviCRM']])
2363 * Add the options appropriate to cid = zero - ie. autocomplete
2365 * @todo there is considerable code duplication between the contribution forms & event forms. It is apparent
2366 * that small pieces of duplication are not being refactored into separate functions because their only shared parent
2367 * is this form. Inserting a class FrontEndForm.php between the contribution & event & this class would allow functions like this
2368 * and a dozen other small ones to be refactored into a shared parent with the reduction of much code duplication
2370 public function addCIDZeroOptions() {
2371 $this->assign('nocid', TRUE);
2373 if ($this->_values
['custom_pre_id']) {
2374 $profiles[] = $this->_values
['custom_pre_id'];
2376 if ($this->_values
['custom_post_id']) {
2377 $profiles = array_merge($profiles, (array) $this->_values
['custom_post_id']);
2379 $profiles[] = 'billing';
2380 if (!empty($this->_values
)) {
2381 $this->addAutoSelector($profiles);
2386 * Set default values on form for given contact (or no contact defaults)
2388 * @param mixed $profile_id
2389 * (can be id, or profile name).
2390 * @param int $contactID
2394 public function getProfileDefaults($profile_id = 'Billing', $contactID = NULL) {
2396 $defaults = civicrm_api3('profile', 'getsingle', [
2397 'profile_id' => (array) $profile_id,
2398 'contact_id' => $contactID,
2402 catch (Exception
$e) {
2403 // the try catch block gives us silent failure -not 100% sure this is a good idea
2404 // as silent failures are often worse than noisy ones
2410 * Sets form attribute.
2413 public function preventAjaxSubmit() {
2414 $this->setAttribute('data-no-ajax-submit', 'true');
2418 * Sets form attribute.
2421 public function allowAjaxSubmit() {
2422 $this->removeAttribute('data-no-ajax-submit');
2426 * Sets page title based on entity and action.
2427 * @param string $entityLabel
2429 public function setPageTitle($entityLabel) {
2430 switch ($this->_action
) {
2431 case CRM_Core_Action
::ADD
:
2432 $this->setTitle(ts('New %1', [1 => $entityLabel]));
2435 case CRM_Core_Action
::UPDATE
:
2436 $this->setTitle(ts('Edit %1', [1 => $entityLabel]));
2439 case CRM_Core_Action
::VIEW
:
2440 case CRM_Core_Action
::PREVIEW
:
2441 $this->setTitle(ts('View %1', [1 => $entityLabel]));
2444 case CRM_Core_Action
::DELETE
:
2445 $this->setTitle(ts('Delete %1', [1 => $entityLabel]));
2451 * Create a chain-select target field. All settings are optional; the defaults usually work.
2453 * @param string $elementName
2454 * @param array $settings
2456 * @return HTML_QuickForm_Element
2458 public function addChainSelect($elementName, $settings = []) {
2459 $required = $settings['required'] ??
FALSE;
2460 $label = strpos($elementName, 'rovince') ? CRM_Core_DAO_StateProvince
::getEntityTitle() : CRM_Core_DAO_County
::getEntityTitle();
2461 $props = $settings +
= [
2462 'control_field' => str_replace(['state_province', 'StateProvince', 'county', 'County'], [
2468 'data-callback' => strpos($elementName, 'rovince') ?
'civicrm/ajax/jqState' : 'civicrm/ajax/jqCounty',
2470 'data-empty-prompt' => strpos($elementName, 'rovince') ?
ts('Choose country first') : ts('Choose state first'),
2471 'data-none-prompt' => ts('- N/A -'),
2472 'multiple' => FALSE,
2473 'required' => $required,
2474 'placeholder' => ts('- select %1 -', [1 => $label]),
2476 CRM_Utils_Array
::remove($props, 'label', 'required', 'control_field', 'context');
2477 $props['class'] = (empty($props['class']) ?
'' : "{$props['class']} ") . 'crm-select2' . ($required ?
' required crm-field-required' : '');
2478 $props['data-select-prompt'] = $props['placeholder'];
2479 $props['data-name'] = $elementName;
2481 $this->_chainSelectFields
[$settings['control_field']] = $elementName;
2483 // Passing NULL instead of an array of options
2484 // CRM-15225 - normally QF will reject any selected values that are not part of the field's options, but due to a
2485 // quirk in our patched version of HTML_QuickForm_select, this doesn't happen if the options are NULL
2486 // which seems a bit dirty but it allows our dynamically-popuplated select element to function as expected.
2487 return $this->add('select', $elementName, $settings['label'], NULL, $required, $props);
2491 * Add actions menu to results form.
2493 * @param array $tasks
2495 public function addTaskMenu($tasks) {
2496 if (is_array($tasks) && !empty($tasks)) {
2497 // Set constants means this will always load with an empty value, not reloading any submitted value.
2498 // This is appropriate as it is a pseudofield.
2499 $this->setConstants(['task' => '']);
2500 $this->assign('taskMetaData', $tasks);
2501 $select = $this->add('select', 'task', NULL, ['' => ts('Actions')], FALSE, [
2502 'class' => 'crm-select2 crm-action-menu fa-check-circle-o huge crm-search-result-actions',
2505 foreach ($tasks as $key => $task) {
2507 if (isset($task['data'])) {
2508 foreach ($task['data'] as $dataKey => $dataValue) {
2509 $attributes['data-' . $dataKey] = $dataValue;
2512 $select->addOption($task['title'], $key, $attributes);
2514 if (empty($this->_actionButtonName
)) {
2515 $this->_actionButtonName
= $this->getButtonName('next', 'action');
2517 $this->assign('actionButtonName', $this->_actionButtonName
);
2518 $this->add('xbutton', $this->_actionButtonName
, ts('Go'), [
2520 'class' => 'hiddenElement crm-search-go-button',
2523 // Radio to choose "All items" or "Selected items only"
2524 $selectedRowsRadio = $this->addElement('radio', 'radio_ts', NULL, '', 'ts_sel', ['checked' => 'checked']);
2525 $allRowsRadio = $this->addElement('radio', 'radio_ts', NULL, '', 'ts_all');
2526 $this->assign('ts_sel_id', $selectedRowsRadio->_attributes
['id']);
2527 $this->assign('ts_all_id', $allRowsRadio->_attributes
['id']);
2529 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header');
2534 * Set options and attributes for chain select fields based on the controlling field's value
2536 private function preProcessChainSelectFields() {
2537 foreach ($this->_chainSelectFields
as $control => $target) {
2538 // The 'target' might get missing if extensions do removeElement() in a form hook.
2539 if ($this->elementExists($target)) {
2540 $targetField = $this->getElement($target);
2541 $targetType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ?
'county' : 'stateProvince';
2543 // If the control field is on the form, setup chain-select and dynamically populate options
2544 if ($this->elementExists($control)) {
2545 $controlField = $this->getElement($control);
2546 $controlType = $targetType == 'county' ?
'stateProvince' : 'country';
2548 $targetField->setAttribute('class', $targetField->getAttribute('class') . ' crm-chain-select-target');
2550 $css = (string) $controlField->getAttribute('class');
2551 $controlField->updateAttributes([
2552 'class' => ($css ?
"$css " : 'crm-select2 ') . 'crm-chain-select-control',
2553 'data-target' => $target,
2555 $controlValue = $controlField->getValue();
2556 if ($controlValue) {
2557 $options = CRM_Core_BAO_Location
::getChainSelectValues($controlValue, $controlType, TRUE);
2559 $targetField->setAttribute('placeholder', $targetField->getAttribute('data-none-prompt'));
2563 $targetField->setAttribute('placeholder', $targetField->getAttribute('data-empty-prompt'));
2564 $targetField->setAttribute('disabled', 'disabled');
2567 // Control field not present - fall back to loading default options
2569 $options = CRM_Core_PseudoConstant
::$targetType();
2571 if (!$targetField->getAttribute('multiple')) {
2572 $options = ['' => $targetField->getAttribute('placeholder')] +
$options;
2573 $targetField->removeAttribute('placeholder');
2575 $targetField->_options
= [];
2576 $targetField->loadArray($options);
2582 * Validate country / state / county match and suppress unwanted "required" errors
2584 private function validateChainSelectFields() {
2585 foreach ($this->_chainSelectFields
as $control => $target) {
2586 if ($this->elementExists($control) && $this->elementExists($target)) {
2587 $controlValue = (array) $this->getElementValue($control);
2588 $targetField = $this->getElement($target);
2589 $controlType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ?
'stateProvince' : 'country';
2590 $targetValue = array_filter((array) $targetField->getValue());
2591 if ($targetValue ||
$this->getElementError($target)) {
2592 $options = CRM_Core_BAO_Location
::getChainSelectValues($controlValue, $controlType, TRUE);
2594 if (!array_intersect($targetValue, array_keys($options))) {
2595 $this->setElementError($target, $controlType == 'country' ?
ts('State/Province does not match the selected Country') : ts('County does not match the selected State/Province'));
2598 // Suppress "required" error for field if it has no options
2599 elseif (!$options) {
2600 $this->setElementError($target, NULL);
2608 * Assign billing name to the template.
2610 * @param array $params
2611 * Form input params, default to $this->_params.
2615 public function assignBillingName($params = []) {
2617 if (empty($params)) {
2618 $params = $this->_params
;
2620 if (!empty($params['billing_first_name'])) {
2621 $name = $params['billing_first_name'];
2624 if (!empty($params['billing_middle_name'])) {
2625 $name .= " {$params['billing_middle_name']}";
2628 if (!empty($params['billing_last_name'])) {
2629 $name .= " {$params['billing_last_name']}";
2631 $name = trim($name);
2632 $this->assign('billingName', $name);
2637 * Get the currency for the form.
2639 * @todo this should be overriden on the forms rather than having this
2640 * historic, possible handling in here. As we clean that up we should
2641 * add deprecation notices into here.
2643 * @param array $submittedValues
2644 * Array allowed so forms inheriting this class do not break.
2645 * Ideally we would make a clear standard around how submitted values
2646 * are stored (is $this->_values consistently doing that?).
2650 public function getCurrency($submittedValues = []) {
2651 $currency = $this->_values
['currency'] ??
NULL;
2652 // For event forms, currency is in a different spot
2653 if (empty($currency)) {
2654 $currency = CRM_Utils_Array
::value('currency', CRM_Utils_Array
::value('event', $this->_values
));
2656 if (empty($currency)) {
2657 $currency = CRM_Utils_Request
::retrieveValue('currency', 'String');
2659 // @todo If empty there is a problem - we should probably put in a deprecation notice
2660 // to warn if that seems to be happening.
2665 * Is the form in view or edit mode.
2667 * The 'addField' function relies on the form action being one of a set list
2668 * of actions. Checking for these allows for an early return.
2672 protected function isFormInViewOrEditMode() {
2673 return $this->isFormInViewMode() ||
$this->isFormInEditMode();
2677 * Is the form in edit mode.
2679 * Helper function, notably for extensions implementing the buildForm hook,
2680 * so that they can return early.
2684 public function isFormInEditMode() {
2685 return in_array($this->_action
, [
2686 CRM_Core_Action
::UPDATE
,
2687 CRM_Core_Action
::ADD
,
2688 CRM_Core_Action
::BROWSE
,
2689 CRM_Core_Action
::BASIC
,
2690 CRM_Core_Action
::ADVANCED
,
2691 CRM_Core_Action
::PREVIEW
,
2696 * Is the form in view mode.
2698 * Helper function, notably for extensions implementing the buildForm hook,
2699 * so that they can return early.
2703 public function isFormInViewMode() {
2704 return $this->_action
== CRM_Core_Action
::VIEW
;
2708 * Set the active tab
2710 * @param string $default
2712 * @throws \CRM_Core_Exception
2714 public function setSelectedChild($default = NULL) {
2715 $selectedChild = CRM_Utils_Request
::retrieve('selectedChild', 'Alphanumeric', $this, FALSE, $default);
2716 if (!empty($selectedChild)) {
2717 $this->set('selectedChild', $selectedChild);
2718 $this->assign('selectedChild', $selectedChild);
2719 Civi
::resources()->addSetting(['tabSettings' => ['active' => $selectedChild]]);
2724 * Get the contact if from the url, using the checksum or the cid if it is the logged in user.
2726 * This function returns the user being validated. It is not intended to get another user
2727 * they have permission to (setContactID does do that) and can be used to check if the user is
2728 * accessing their own record.
2731 * @throws \CRM_Core_Exception
2733 protected function getContactIDIfAccessingOwnRecord() {
2734 $contactID = (int) CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
2738 if ($contactID === CRM_Core_Session
::getLoggedInContactID()) {
2741 $userChecksum = CRM_Utils_Request
::retrieve('cs', 'String', $this);
2742 return CRM_Contact_BAO_Contact_Utils
::validChecksum($contactID, $userChecksum) ?
$contactID : FALSE;
2746 * Get values submitted by the user.
2748 * These values have been validated against the fields added to the form.
2749 * https://pear.php.net/manual/en/package.html.html-quickform.html-quickform.exportvalues.php
2751 * @param string $fieldName
2753 * @return mixed|null
2755 public function getSubmittedValue(string $fieldName) {
2756 if (empty($this->exportedValues
)) {
2757 $this->exportedValues
= $this->controller
->exportValues($this->_name
);
2759 $value = $this->exportedValues
[$fieldName] ??
NULL;
2760 if (in_array($fieldName, $this->submittableMoneyFields
, TRUE)) {
2761 return CRM_Utils_Rule
::cleanMoney($value);
2767 * Get the active UFGroups (profiles) on this form
2768 * Many forms load one or more UFGroups (profiles).
2769 * This provides a standard function to retrieve the IDs of those profiles from the form
2770 * so that you can implement things such as "is is_captcha field set on any of the active profiles on this form?"
2772 * NOT SUPPORTED FOR USE OUTSIDE CORE EXTENSIONS - Added for reCAPTCHA core extension.
2776 public function getUFGroupIDs() {