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'),
145 protected $_dateFields = [];
148 * Cache the smarty template for efficiency reasons
150 * @var CRM_Core_Smarty
152 static protected $_template;
155 * Indicate if this form should warn users of unsaved changes
158 protected $unsavedChangesWarn;
161 * What to return to the client if in ajax mode (snippet=json)
165 public $ajaxResponse = [];
168 * Url path used to reach this page
172 public $urlPath = [];
175 * Context of the form being loaded.
186 public $submitOnce = FALSE;
189 * Values submitted by the user.
191 * These values have been checked for injection per
192 * https://pear.php.net/manual/en/package.html.html-quickform.html-quickform.exportvalues.php
193 * and are as submitted.
195 * Once set this array should be treated as read only.
199 protected $exportedValues = [];
204 public function getContext() {
205 return $this->context
;
209 * Set context variable.
211 public function setContext() {
212 $this->context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
216 * @var CRM_Core_Controller
221 * Constants for attributes for various form elements
222 * attempt to standardize on the number of variations that we
223 * use of the below form elements
227 const ATTR_SPACING
= ' ';
230 * All checkboxes are defined with a common prefix. This allows us to
231 * have the same javascript to check / clear all the checkboxes etc
232 * If u have multiple groups of checkboxes, you will need to give them different
233 * ids to avoid potential name collision
237 const CB_PREFIX
= 'mark_x_', CB_PREFIY
= 'mark_y_', CB_PREFIZ
= 'mark_z_', CB_PREFIX_LEN
= 7;
241 * @internal to keep track of chain-select fields
243 private $_chainSelectFields = [];
246 * Extra input types we support via the "add" method
249 public static $html5Types = [
257 * Variables smarty expects to have set.
259 * We ensure these are assigned (value = NULL) when Smarty is instantiated in
260 * order to avoid e-notices / having to use empty or isset in the template layer.
264 public $expectedSmartyVariables = [
272 'beginHookFormElements',
273 // required for footer.tpl
275 // required for info.tpl
280 // required for attachmentjs.tpl
282 // FormButtons.tpl (adds buttons to forms).
284 // Required for contactFooter.tpl.
285 // See CRM_Activity_Form_ActivityTest:testInboundEmailDisplaysWithLineBreaks.
286 'external_identifier',
290 // Required for footer.tpl,
291 // See CRM_Activity_Form_ActivityTest:testInboundEmailDisplaysWithLineBreaks.
292 'footer_status_severity',
296 * Constructor for the basic form page.
298 * We should not use QuickForm directly. This class provides a lot
299 * of default convenient functions, rules and buttons
301 * @param object $state
302 * State associated with this form.
303 * @param int $action The mode the form is operating in (None/Create/View/Update/Delete)
304 * @param string $method
305 * The type of http method used (GET/POST).
306 * @param string $name
307 * The name of the form if different from class name.
309 * @return \CRM_Core_Form
311 public function __construct(
313 $action = CRM_Core_Action
::NONE
,
319 $this->_name
= $name;
322 // CRM-15153 - FIXME this name translates to a DOM id and is not always unique!
323 $this->_name
= CRM_Utils_String
::getClassName(CRM_Utils_System
::getClassName($this));
326 parent
::__construct($this->_name
, $method);
328 $this->_state
=& $state;
330 $this->_state
->setName($this->_name
);
332 $this->_action
= (int) $action;
334 $this->registerRules();
336 // let the constructor initialize this, should happen only once
337 if (!isset(self
::$_template)) {
338 self
::$_template = CRM_Core_Smarty
::singleton();
341 // Workaround for CRM-15153 - give each form a reasonably unique css class
342 $this->addClass(CRM_Utils_System
::getClassName($this));
344 $this->assign('snippet', CRM_Utils_Array
::value('snippet', $_GET));
345 $this->setTranslatedFields();
349 * Set translated fields.
351 * This function is called from the class constructor, allowing us to set
352 * fields on the class that can't be set as properties due to need for
353 * translation or other non-input specific handling.
355 protected function setTranslatedFields() {}
358 * Add one or more css classes to the form.
360 * @param string $className
362 public function addClass($className) {
363 $classes = $this->getAttribute('class');
364 $this->setAttribute('class', ($classes ?
"$classes " : '') . $className);
368 * Register all the standard rules that most forms potentially use.
370 public function registerRules() {
399 foreach ($rules as $rule) {
400 $this->registerRule($rule, 'callback', $rule, 'CRM_Utils_Rule');
405 * Simple easy to use wrapper around addElement.
407 * Deal with simple validation rules.
409 * @param string $type
410 * @param string $name
411 * @param string $label
412 * @param array $attributes (options for select elements)
413 * @param bool $required
414 * @param array $extra
415 * (attributes for select elements).
416 * For datepicker elements this is consistent with the data
417 * from CRM_Utils_Date::getDatePickerExtra
419 * @return HTML_QuickForm_Element
420 * Could be an error object
422 * @throws \CRM_Core_Exception
424 public function &add(
425 $type, $name, $label = '',
426 $attributes = NULL, $required = FALSE, $extra = NULL
428 if ($type === 'radio') {
429 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_Form::addRadio');
432 if ($type !== 'static' && $attributes && !is_array($attributes)) {
433 // The $attributes param used to allow for strings and would default to an
434 // empty string. However, now that the variable is heavily manipulated,
435 // we should expect it to always be an array.
436 CRM_Core_Error
::deprecatedWarning('Attributes passed to CRM_Core_Form::add() are not an array.');
438 // Fudge some extra types that quickform doesn't support
440 if ($type == 'wysiwyg' ||
in_array($type, self
::$html5Types)) {
441 $attributes = ($attributes ?
$attributes : []) +
['class' => ''];
442 $attributes['class'] = ltrim($attributes['class'] . " crm-form-$type");
443 if ($type == 'wysiwyg' && isset($attributes['preset'])) {
444 $attributes['data-preset'] = $attributes['preset'];
445 unset($attributes['preset']);
447 $type = $type == 'wysiwyg' ?
'textarea' : 'text';
449 // Like select but accepts rich array data (with nesting, colors, icons, etc) as option list.
450 if ($inputType == 'select2') {
452 $options = $attributes;
453 $attributes = ($extra ?
$extra : []) +
['class' => ''];
454 $attributes['class'] = ltrim($attributes['class'] . " crm-select2 crm-form-select2");
455 $attributes['data-select-params'] = json_encode(['data' => $options, 'multiple' => !empty($attributes['multiple'])]);
456 unset($attributes['multiple']);
460 // @see https://docs.civicrm.org/dev/en/latest/framework/ui/#date-picker
461 if ($type === 'datepicker') {
462 $attributes = $attributes ?
: [];
463 if (!empty($attributes['formatType'])) {
464 $dateAttributes = CRM_Core_SelectValues
::date($attributes['formatType'], NULL, NULL, NULL, 'Input');
465 if (empty($extra['minDate']) && !empty($dateAttributes['minYear'])) {
466 $extra['minDate'] = $dateAttributes['minYear'] . '-01-01';
468 if (empty($extra['maxDate']) && !empty($dateAttributes['minYear'])) {
469 $extra['maxDate'] = $dateAttributes['maxYear'] . '-12-31';
472 // Support minDate/maxDate properties
473 if (isset($extra['minDate'])) {
474 $extra['minDate'] = date('Y-m-d', strtotime($extra['minDate']));
476 if (isset($extra['maxDate'])) {
477 $extra['maxDate'] = date('Y-m-d', strtotime($extra['maxDate']));
480 $attributes['data-crm-datepicker'] = json_encode((array) $extra);
481 if (!empty($attributes['aria-label']) ||
$label) {
482 $attributes['aria-label'] = $attributes['aria-label'] ??
$label;
486 if ($type === 'select' && is_array($extra)) {
487 // Normalize this property
488 if (!empty($extra['multiple'])) {
489 $extra['multiple'] = 'multiple';
492 unset($extra['multiple']);
494 unset($extra['size'], $extra['maxlength']);
495 // Add placeholder option for select
496 if (isset($extra['placeholder'])) {
497 if ($extra['placeholder'] === TRUE) {
498 $extra['placeholder'] = ts('- select %1 -', [1 => $label]);
500 if (($extra['placeholder'] ||
$extra['placeholder'] === '') && empty($extra['multiple']) && is_array($attributes) && !isset($attributes[''])) {
501 $attributes = ['' => $extra['placeholder']] +
$attributes;
505 $optionContext = NULL;
506 if (!empty($extra['option_context'])) {
507 $optionContext = $extra['option_context'];
508 unset($extra['option_context']);
511 $element = $this->addElement($type, $name, CRM_Utils_String
::purifyHTML($label), $attributes, $extra);
512 if (HTML_QuickForm
::isError($element)) {
513 CRM_Core_Error
::statusBounce(HTML_QuickForm
::errorMessage($element));
516 if ($inputType == 'color') {
517 $this->addRule($name, ts('%1 must contain a color value e.g. #ffffff.', [1 => $label]), 'regex', '/#[0-9a-fA-F]{6}/');
521 if ($type == 'file') {
522 $error = $this->addRule($name, ts('%1 is a required field.', [1 => $label]), 'uploadedfile');
525 $error = $this->addRule($name, ts('%1 is a required field.', [1 => $label]), 'required');
527 if (HTML_QuickForm
::isError($error)) {
528 CRM_Core_Error
::statusBounce(HTML_QuickForm
::errorMessage($element));
532 // Add context for the editing of option groups
533 if ($optionContext) {
534 $element->setAttribute('data-option-edit-context', json_encode($optionContext));
543 * This is called before buildForm. Any pre-processing that
544 * needs to be done for buildForm should be done here.
546 * This is a virtual function and should be redefined if needed.
548 public function preProcess() {
552 * Called after the form is validated.
554 * Any processing of form state etc should be done in this function.
555 * Typically all processing associated with a form should be done
556 * here and relevant state should be stored in the session
558 * This is a virtual function and should be redefined if needed
560 public function postProcess() {
564 * Main process wrapper.
566 * Implemented so that we can call all the hook functions.
568 * @param bool $allowAjax
569 * FIXME: This feels kind of hackish, ideally we would take the json-related code from this function.
570 * and bury it deeper down in the controller
572 public function mainProcess($allowAjax = TRUE) {
573 $this->postProcess();
574 $this->postProcessHook();
576 // Respond with JSON if in AJAX context (also support legacy value '6')
577 if ($allowAjax && !empty($_REQUEST['snippet']) && in_array($_REQUEST['snippet'], [
578 CRM_Core_Smarty
::PRINT_JSON
,
581 $this->ajaxResponse
['buttonName'] = str_replace('_qf_' . $this->getAttribute('id') . '_', '', $this->controller
->getButtonName());
582 $this->ajaxResponse
['action'] = $this->_action
;
583 if (isset($this->_id
) ||
isset($this->id
)) {
584 $this->ajaxResponse
['id'] = $this->id ??
$this->_id
;
586 CRM_Core_Page_AJAX
::returnJsonResponse($this->ajaxResponse
);
591 * The postProcess hook is typically called by the framework.
593 * However in a few cases, the form exits or redirects early in which
594 * case it needs to call this function so other modules can do the needful
595 * Calling this function directly should be avoided if possible. In general a
596 * better way is to do setUserContext so the framework does the redirect
598 public function postProcessHook() {
599 CRM_Utils_Hook
::postProcess(get_class($this), $this);
603 * This virtual function is used to build the form.
605 * It replaces the buildForm associated with QuickForm_Page. This allows us to put
606 * preProcess in front of the actual form building routine
608 public function buildQuickForm() {
612 * This virtual function is used to set the default values of various form elements.
615 * reference to the array of default values
617 public function setDefaultValues() {
622 * This is a virtual function that adds group and global rules to the form.
624 * Keeping it distinct from the form to keep code small
625 * and localized in the form building code
627 public function addRules() {
631 * Performs the server side validation.
634 * true if no error found
635 * @throws HTML_QuickForm_Error
637 public function validate() {
638 $error = parent
::validate();
640 $this->validateChainSelectFields();
644 CRM_Utils_Hook
::validateForm(
646 $this->_submitValues
,
652 if (!empty($hookErrors)) {
653 $this->_errors +
= $hookErrors;
656 return (0 == count($this->_errors
));
660 * Core function that builds the form.
662 * We redefine this function here and expect all CRM forms to build their form in the function
665 public function buildForm() {
666 $this->_formBuilt
= TRUE;
670 CRM_Utils_Hook
::preProcess(get_class($this), $this);
672 $this->assign('translatePermission', CRM_Core_Permission
::check('translate CiviCRM'));
675 $this->controller
->_key
&&
676 $this->controller
->_generateQFKey
678 $this->addElement('hidden', 'qfKey', $this->controller
->_key
);
679 $this->assign('qfKey', $this->controller
->_key
);
683 // _generateQFKey suppresses the qfKey generation on form snippets that
684 // are part of other forms, hence we use that to avoid adding entryURL
685 if ($this->controller
->_generateQFKey
&& $this->controller
->_entryURL
) {
686 $this->addElement('hidden', 'entryURL', $this->controller
->_entryURL
);
689 $this->buildQuickForm();
691 $defaults = $this->setDefaultValues();
692 unset($defaults['qfKey']);
694 if (!empty($defaults)) {
695 $this->setDefaults($defaults);
698 // call the form hook
699 // also call the hook function so any modules can set their own custom defaults
700 // the user can do both the form and set default values with this hook
701 CRM_Utils_Hook
::buildForm(get_class($this), $this);
705 //Set html data-attribute to enable warning user of unsaved changes
706 if ($this->unsavedChangesWarn
=== TRUE
707 ||
(!isset($this->unsavedChangesWarn
)
708 && ($this->_action
& CRM_Core_Action
::ADD ||
$this->_action
& CRM_Core_Action
::UPDATE
)
711 $this->setAttribute('data-warn-changes', 'true');
714 if ($this->submitOnce
) {
715 $this->setAttribute('data-submit-once', 'true');
717 // Smarty $_template is a static var which persists between tests, so
718 // if something calls clearTemplateVars(), the static still exists but
719 // our ensured variables get blown away, so we need to set them even if
720 // it's already been initialized.
721 self
::$_template->ensureVariablesAreAssigned($this->expectedSmartyVariables
);
726 * Add default Next / Back buttons.
728 * @param array $params
729 * Array of associative arrays in the order in which the buttons should be
730 * displayed. The associate array has 3 fields: 'type', 'name' and 'isDefault'
731 * The base form class will define a bunch of static arrays for commonly used
734 public function addButtons($params) {
735 $prevnext = $spacing = [];
736 foreach ($params as $button) {
737 if (!empty($button['submitOnce'])) {
738 $this->submitOnce
= TRUE;
741 $attrs = ['class' => 'crm-form-submit'] +
(array) CRM_Utils_Array
::value('js', $button);
743 // A lot of forms use the hacky method of looking at
744 // `$params['button name']` (dating back to them being inputs with a
745 // "value" of the button label) rather than looking at
746 // `$this->controller->getButtonName()`. It makes sense to give buttons a
747 // value by default as a precaution.
750 if (!empty($button['class'])) {
751 $attrs['class'] .= ' ' . $button['class'];
754 if (!empty($button['isDefault'])) {
755 $attrs['class'] .= ' default';
758 if (in_array($button['type'], ['upload', 'next', 'submit', 'done', 'process', 'refresh'])) {
759 $attrs['class'] .= ' validate';
760 $defaultIcon = 'fa-check';
763 $attrs['class'] .= ' cancel';
764 $defaultIcon = $button['type'] == 'back' ?
'fa-chevron-left' : 'fa-times';
767 if ($button['type'] === 'reset') {
768 $attrs['type'] = 'reset';
769 $prevnext[] = $this->createElement('xbutton', 'reset', $button['name'], $attrs);
772 if (!empty($button['subName'])) {
773 if ($button['subName'] == 'new') {
774 $defaultIcon = 'fa-plus-circle';
776 if ($button['subName'] == 'done') {
777 $defaultIcon = 'fa-check-circle';
779 if ($button['subName'] == 'next') {
780 $defaultIcon = 'fa-chevron-right';
784 if (in_array($button['type'], ['next', 'upload', 'done']) && $button['name'] === ts('Save')) {
785 $attrs['accesskey'] = 'S';
787 $buttonContents = CRM_Core_Page
::crmIcon($button['icon'] ??
$defaultIcon) . ' ' . $button['name'];
788 $buttonName = $this->getButtonName($button['type'], CRM_Utils_Array
::value('subName', $button));
789 $attrs['class'] .= " crm-button crm-button-type-{$button['type']} crm-button{$buttonName}";
790 $attrs['type'] = 'submit';
791 $prevnext[] = $this->createElement('xbutton', $buttonName, $buttonContents, $attrs);
793 if (!empty($button['isDefault'])) {
794 $this->setDefaultAction($button['type']);
797 // if button type is upload, set the enctype
798 if ($button['type'] == 'upload') {
799 $this->updateAttributes(['enctype' => 'multipart/form-data']);
800 $this->setMaxFileSize();
803 // hack - addGroup uses an array to express variable spacing, read from the last element
804 $spacing[] = CRM_Utils_Array
::value('spacing', $button, self
::ATTR_SPACING
);
806 $this->addGroup($prevnext, 'buttons', '', $spacing, FALSE);
810 * Getter function for Name.
814 public function getName() {
819 * Getter function for State.
823 public function &getState() {
824 return $this->_state
;
828 * Getter function for StateType.
832 public function getStateType() {
833 return $this->_state
->getType();
837 * Getter function for title.
839 * Should be over-ridden by derived class.
843 public function getTitle() {
844 return $this->_title ?
$this->_title
: ts('ERROR: Title is not Set');
848 * Setter function for title.
850 * @param string $title
851 * The title of the form.
853 public function setTitle($title) {
854 $this->_title
= $title;
855 CRM_Utils_System
::setTitle($title);
859 * Assign billing type id to bltID.
861 * @throws CRM_Core_Exception
863 public function assignBillingType() {
864 $this->_bltID
= CRM_Core_BAO_LocationType
::getBilling();
865 $this->set('bltID', $this->_bltID
);
866 $this->assign('bltID', $this->_bltID
);
872 public function getPaymentProcessorID(): int {
873 return (int) $this->_paymentProcessorID
;
877 * This if a front end form function for setting the payment processor.
879 * It would be good to sync it with the back-end function on abstractEditPayment & use one everywhere.
881 * @param bool $isPayLaterEnabled
883 * @throws \CRM_Core_Exception
885 protected function assignPaymentProcessor($isPayLaterEnabled) {
886 $this->_paymentProcessors
= CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors([ucfirst($this->_mode
) . 'Mode'], $this->_paymentProcessorIDs
);
887 if ($isPayLaterEnabled) {
888 $this->_paymentProcessors
[0] = CRM_Financial_BAO_PaymentProcessor
::getPayment(0);
891 if (!empty($this->_paymentProcessors
)) {
892 foreach ($this->_paymentProcessors
as $paymentProcessorID => $paymentProcessorDetail) {
893 if (empty($this->_paymentProcessor
) && $paymentProcessorDetail['is_default'] == 1 ||
(count($this->_paymentProcessors
) == 1)
895 $this->_paymentProcessor
= $paymentProcessorDetail;
896 $this->assign('paymentProcessor', $this->_paymentProcessor
);
897 // Setting this is a bit of a legacy overhang.
898 $this->_paymentObject
= $paymentProcessorDetail['object'];
901 // It's not clear why we set this on the form.
902 $this->set('paymentProcessors', $this->_paymentProcessors
);
907 * Assign an array of variables to the form/tpl
909 * @param array $values Array of [key => value] to assign to the form
910 * @param array $keys Array of keys to assign from the values array
912 public function assignVariables($values, $keys) {
913 foreach ($keys as $key) {
914 $this->assign($key, $values[$key] ??
NULL);
919 * Format the fields in $this->_params for the payment processor.
921 * In order to pass fields to the payment processor in a consistent way we add some renamed
924 * @param array $fields
928 protected function formatParamsForPaymentProcessor($fields) {
929 $this->_params
= $this->prepareParamsForPaymentProcessor($this->_params
);
930 $fields = array_merge($fields, ['first_name' => 1, 'middle_name' => 1, 'last_name' => 1]);
935 * Format the fields in $params for the payment processor.
937 * In order to pass fields to the payment processor in a consistent way we add some renamed
940 * @param array $params Payment processor params
942 * @return array $params
944 protected function prepareParamsForPaymentProcessor($params) {
945 // also add location name to the array
946 $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);
947 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
948 // Add additional parameters that the payment processors are used to receiving.
949 if (!empty($params["billing_state_province_id-{$this->_bltID}"])) {
950 $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}"]);
952 if (!empty($params["billing_country_id-{$this->_bltID}"])) {
953 $params['country'] = $params["country-{$this->_bltID}"] = $params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($params["billing_country_id-{$this->_bltID}"]);
956 [$hasAddressField, $addressParams] = CRM_Contribute_BAO_Contribution
::getPaymentProcessorReadyAddressParams($params, $this->_bltID
);
957 if ($hasAddressField) {
958 $params = array_merge($params, $addressParams);
961 // How does this relate to similar code in CRM_Contact_BAO_Contact::addBillingNameFieldsIfOtherwiseNotSet()?
962 $nameFields = ['first_name', 'middle_name', 'last_name'];
963 foreach ($nameFields as $name) {
964 if (array_key_exists("billing_$name", $params)) {
965 $params[$name] = $params["billing_{$name}"];
966 $params['preserveDBName'] = TRUE;
970 // For legacy reasons we set these creditcard expiry fields if present
971 CRM_Contribute_Form_AbstractEditPayment
::formatCreditCardDetails($params);
973 // Assign IP address parameter
974 $params['ip_address'] = CRM_Utils_System
::ipAddress();
980 * Handle Payment Processor switching for contribution and event registration forms.
982 * This function is shared between contribution & event forms & this is their common class.
984 * However, this should be seen as an in-progress refactor, the end goal being to also align the
985 * backoffice forms that action payments.
987 * This function overlaps assignPaymentProcessor, in a bad way.
989 protected function preProcessPaymentOptions() {
990 $this->_paymentProcessorID
= NULL;
991 if ($this->_paymentProcessors
) {
992 if (!empty($this->_submitValues
)) {
993 $this->_paymentProcessorID
= $this->_submitValues
['payment_processor_id'] ??
NULL;
994 $this->_paymentProcessor
= $this->_paymentProcessors
[$this->_paymentProcessorID
] ??
NULL;
995 $this->set('type', $this->_paymentProcessorID
);
996 $this->set('mode', $this->_mode
);
997 $this->set('paymentProcessor', $this->_paymentProcessor
);
999 // Set default payment processor
1001 foreach ($this->_paymentProcessors
as $values) {
1002 if (!empty($values['is_default']) ||
count($this->_paymentProcessors
) == 1) {
1003 $this->_paymentProcessorID
= $values['id'];
1008 if ($this->_paymentProcessorID
1009 ||
(isset($this->_submitValues
['payment_processor_id']) && $this->_submitValues
['payment_processor_id'] == 0)
1011 CRM_Core_Payment_ProcessorForm
::preProcess($this);
1014 $this->_paymentProcessor
= [];
1018 // We save the fact that the profile 'billing' is required on the payment form.
1019 // Currently pay-later is the only 'processor' that takes notice of this - but ideally
1020 // 1) it would be possible to select the minimum_billing_profile_id for the contribution form
1021 // 2) that profile_id would be set on the payment processor
1022 // 3) the payment processor would return a billing form that combines these user-configured
1023 // minimums with the payment processor minimums. This would lead to fields like 'postal_code'
1024 // only being on the form if either the admin has configured it as wanted or the processor
1026 $this->assign('billing_profile_id', (!empty($this->_values
['is_billing_required']) ?
'billing' : ''));
1030 * Handle pre approval for processors.
1032 * This fits with the flow where a pre-approval is done and then confirmed in the next stage when confirm is hit.
1034 * This function is shared between contribution & event forms & this is their common class.
1036 * However, this should be seen as an in-progress refactor, the end goal being to also align the
1037 * backoffice forms that action payments.
1039 * @param array $params
1041 protected function handlePreApproval(&$params) {
1043 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1044 $params['component'] = $params['component'] ??
'contribute';
1045 $result = $payment->doPreApproval($params);
1046 if (empty($result)) {
1047 // This could happen, for example, when paypal looks at the button value & decides it is not paypal express.
1051 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
1052 CRM_Core_Error
::statusBounce(ts('Payment approval failed with message :') . $e->getMessage(), $payment->getCancelUrl($params['qfKey'], CRM_Utils_Array
::value('participant_id', $params)));
1055 $this->set('pre_approval_parameters', $result['pre_approval_parameters']);
1056 if (!empty($result['redirect_url'])) {
1057 CRM_Utils_System
::redirect($result['redirect_url']);
1062 * Setter function for options.
1064 * @param mixed $options
1066 public function setOptions($options) {
1067 $this->_options
= $options;
1071 * Quick form elements which are conditionally added to the form.
1073 * Elements in this array will be added to the form at the end if not present
1074 * so that smarty does not e-notice on things like '{if $form.group}' when
1075 * 'group' is not added to the form (e.g when no groups exist).
1079 protected $optionalQuickFormElements = [];
1082 * Add an optional element to the optional elements array.
1084 * These elements are assigned as empty (null) variables if
1085 * there is no real field - allowing smarty to use them without
1088 * @param string $elementName
1090 public function addOptionalQuickFormElement(string $elementName): void
{
1091 $this->optionalQuickFormElements
[] = $elementName;
1095 * Get any quick-form elements that may not be present in the form.
1097 * To make life simpler for smarty we ensure they are set to null
1098 * rather than unset. This is done at the last minute when $this
1099 * is converted to an array to be assigned to the form.
1103 public function getOptionalQuickFormElements(): array {
1104 return $this->optionalQuickFormElements
;
1108 * Add an expected smarty variable to the array.
1110 * @param string $elementName
1112 public function addExpectedSmartyVariable(string $elementName): void
{
1113 $this->expectedSmartyVariables
[] = $elementName;
1117 * Render form and return contents.
1121 public function toSmarty() {
1122 $this->preProcessChainSelectFields();
1123 $renderer = $this->getRenderer();
1124 $this->accept($renderer);
1125 $content = $renderer->toArray();
1126 $content['formName'] = $this->getName();
1128 $content['formClass'] = CRM_Utils_System
::getClassName($this);
1129 foreach (array_merge($this->getOptionalQuickFormElements(), $this->expectedSmartyVariables
) as $string) {
1130 if (!array_key_exists($string, $content)) {
1131 $content[$string] = NULL;
1138 * Getter function for renderer.
1140 * If renderer is not set create one and initialize it.
1144 public function &getRenderer() {
1145 if (!isset($this->_renderer
)) {
1146 $this->_renderer
= CRM_Core_Form_Renderer
::singleton();
1148 return $this->_renderer
;
1152 * Use the form name to create the tpl file name.
1156 public function getTemplateFileName() {
1157 $ext = CRM_Extension_System
::singleton()->getMapper();
1158 if ($ext->isExtensionClass(CRM_Utils_System
::getClassName($this))) {
1159 $filename = $ext->getTemplateName(CRM_Utils_System
::getClassName($this));
1160 $tplname = $ext->getTemplatePath(CRM_Utils_System
::getClassName($this)) . DIRECTORY_SEPARATOR
. $filename;
1164 CRM_Utils_System
::getClassName($this),
1166 '_' => DIRECTORY_SEPARATOR
,
1167 '\\' => DIRECTORY_SEPARATOR
,
1175 * A wrapper for getTemplateFileName.
1177 * This includes calling the hook to prevent us from having to copy & paste the logic of calling the hook.
1179 public function getHookedTemplateFileName() {
1180 $pageTemplateFile = $this->getTemplateFileName();
1181 CRM_Utils_Hook
::alterTemplateFile(get_class($this), $this, 'page', $pageTemplateFile);
1182 return $pageTemplateFile;
1186 * Default extra tpl file basically just replaces .tpl with .extra.tpl.
1188 * i.e. we do not override.
1192 public function overrideExtraTemplateFileName() {
1197 * Error reporting mechanism.
1199 * @param string $message
1203 * @param CRM_Core_DAO $dao
1204 * A data access object on which we perform a rollback if non - empty.
1206 public function error($message, $code = NULL, $dao = NULL) {
1208 $dao->query('ROLLBACK');
1211 $error = CRM_Core_Error
::singleton();
1213 $error->push($code, $message);
1217 * Store the variable with the value in the form scope.
1219 * @param string $name
1220 * Name of the variable.
1221 * @param mixed $value
1222 * Value of the variable.
1224 public function set($name, $value) {
1225 $this->controller
->set($name, $value);
1229 * Get the variable from the form scope.
1231 * @param string $name
1232 * Name of the variable
1236 public function get($name) {
1237 return $this->controller
->get($name);
1241 * Getter for action.
1245 public function getAction() {
1246 return $this->_action
;
1250 * Setter for action.
1252 * @param int $action
1253 * The mode we want to set the form.
1255 public function setAction($action) {
1256 $this->_action
= $action;
1260 * Assign value to name in template.
1262 * @param string $var
1264 * @param mixed $value
1265 * Value of variable.
1267 public function assign($var, $value = NULL) {
1268 self
::$_template->assign($var, $value);
1272 * Assign value to name in template by reference.
1274 * @param string $var
1276 * @param mixed $value
1277 * Value of variable.
1279 public function assign_by_ref($var, &$value) {
1280 self
::$_template->assign_by_ref($var, $value);
1284 * Appends values to template variables.
1286 * @param array|string $tpl_var the template variable name(s)
1287 * @param mixed $value
1288 * The value to append.
1289 * @param bool $merge
1291 public function append($tpl_var, $value = NULL, $merge = FALSE) {
1292 self
::$_template->append($tpl_var, $value, $merge);
1296 * Returns an array containing template variables.
1298 * @param string $name
1302 public function get_template_vars($name = NULL) {
1303 return self
::$_template->get_template_vars($name);
1307 * @param string $name
1308 * @param string $title
1309 * @param array $values
1310 * @param array $attributes
1311 * @param string $separator
1312 * @param bool $required
1313 * @param array $optionAttributes - Option specific attributes
1315 * @return HTML_QuickForm_group
1317 public function &addRadio($name, $title, $values, $attributes = [], $separator = NULL, $required = FALSE, $optionAttributes = []) {
1319 $attributes = $attributes ?
$attributes : [];
1320 $allowClear = !empty($attributes['allowClear']);
1321 unset($attributes['allowClear']);
1322 $attributes['id_suffix'] = $name;
1323 foreach ($values as $key => $var) {
1324 $optAttributes = $attributes;
1325 if (!empty($optionAttributes[$key])) {
1326 foreach ($optionAttributes[$key] as $optAttr => $optVal) {
1327 $optAttributes[$optAttr] = ltrim(($optAttributes[$optAttr] ??
'') . ' ' . $optVal);
1330 // We use a class here to avoid html5 issues with collapsed cutsomfield sets.
1331 $optAttributes['class'] = $optAttributes['class'] ??
'';
1333 $optAttributes['class'] .= ' required';
1335 $element = $this->createElement('radio', NULL, NULL, $var, $key, $optAttributes);
1336 $options[] = $element;
1338 $group = $this->addGroup($options, $name, $title, $separator);
1340 $optionEditKey = 'data-option-edit-path';
1341 if (!empty($attributes[$optionEditKey])) {
1342 $group->setAttribute($optionEditKey, $attributes[$optionEditKey]);
1346 $this->addRule($name, ts('%1 is a required field.', [1 => $title]), 'required');
1349 $group->setAttribute('allowClear', TRUE);
1356 * @param string $title
1357 * @param bool $allowClear
1358 * @param bool $required
1359 * @param array $attributes
1361 public function addYesNo($id, $title, $allowClear = FALSE, $required = NULL, $attributes = []) {
1362 $attributes +
= ['id_suffix' => $id];
1364 $choice[] = $this->createElement('radio', NULL, '11', ts('Yes'), '1', $attributes);
1365 $choice[] = $this->createElement('radio', NULL, '11', ts('No'), '0', $attributes);
1367 $group = $this->addGroup($choice, $id, $title);
1369 $group->setAttribute('allowClear', TRUE);
1372 $this->addRule($id, ts('%1 is a required field.', [1 => $title]), 'required');
1378 * @param string $title
1379 * @param array $values
1380 * @param null $other
1381 * @param null $attributes
1382 * @param null $required
1383 * @param null $javascriptMethod
1384 * @param string $separator
1385 * @param bool $flipValues
1387 public function addCheckBox(
1388 $id, $title, $values, $other = NULL,
1389 $attributes = NULL, $required = NULL,
1390 $javascriptMethod = NULL,
1391 $separator = '<br />', $flipValues = FALSE
1395 if ($javascriptMethod) {
1396 foreach ($values as $key => $var) {
1398 $options[] = $this->createElement('checkbox', $var, NULL, $key, $javascriptMethod, $attributes);
1401 $options[] = $this->createElement('checkbox', $key, NULL, $var, $javascriptMethod, $attributes);
1406 foreach ($values as $key => $var) {
1408 $options[] = $this->createElement('checkbox', $var, NULL, $key, $attributes);
1411 $options[] = $this->createElement('checkbox', $key, NULL, $var, $attributes);
1416 $group = $this->addGroup($options, $id, $title, $separator);
1417 $optionEditKey = 'data-option-edit-path';
1418 if (!empty($attributes[$optionEditKey])) {
1419 $group->setAttribute($optionEditKey, $attributes[$optionEditKey]);
1423 $this->addElement('text', $id . '_other', ts('Other'), $attributes[$id . '_other']);
1428 ts('%1 is a required field.', [1 => $title]),
1434 public function resetValues() {
1435 $data = $this->controller
->container();
1436 $data['values'][$this->_name
] = [];
1440 * Simple shell that derived classes can call to add buttons to
1441 * the form with a customized title for the main Submit
1443 * @param string $title
1444 * Title of the main button.
1445 * @param string $nextType
1446 * Button type for the form after processing.
1447 * @param string $backType
1448 * @param bool|string $submitOnce
1450 public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
1452 if ($backType != NULL) {
1454 'type' => $backType,
1455 'name' => ts('Previous'),
1458 if ($nextType != NULL) {
1460 'type' => $nextType,
1462 'isDefault' => TRUE,
1465 $this->submitOnce
= TRUE;
1467 $buttons[] = $nextButton;
1469 $this->addButtons($buttons);
1473 * @param string $name
1474 * @param string $from
1476 * @param string $label
1477 * @param string $dateFormat
1478 * @param bool $required
1479 * @param bool $displayTime
1481 public function addDateRange($name, $from = '_from', $to = '_to', $label = 'From:', $dateFormat = 'searchDate', $required = FALSE, $displayTime = FALSE) {
1482 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Core_Form::addDatePickerRange insted');
1484 $this->addDateTime($name . $from, $label, $required, ['formatType' => $dateFormat]);
1485 $this->addDateTime($name . $to, ts('To:'), $required, ['formatType' => $dateFormat]);
1488 $this->addDate($name . $from, $label, $required, ['formatType' => $dateFormat]);
1489 $this->addDate($name . $to, ts('To:'), $required, ['formatType' => $dateFormat]);
1494 * Add a search for a range using date picker fields.
1496 * @param string $fieldName
1497 * @param string $label
1498 * @param bool $isDateTime
1499 * Is this a date-time field (not just date).
1500 * @param bool $required
1501 * @param string $fromLabel
1502 * @param string $toLabel
1503 * @param array $additionalOptions
1504 * @param string $to string to append to the to field.
1505 * @param string $from string to append to the from field.
1507 public function addDatePickerRange($fieldName, $label, $isDateTime = FALSE, $required = FALSE, $fromLabel = 'From', $toLabel = 'To', $additionalOptions = [],
1508 $to = '_high', $from = '_low') {
1511 '' => ts('- any -'),
1512 0 => ts('Choose Date Range'),
1513 ] + CRM_Core_OptionGroup
::values('relative_date_filters');
1515 if ($additionalOptions) {
1516 foreach ($additionalOptions as $key => $optionLabel) {
1517 $options[$key] = $optionLabel;
1521 $this->add('select',
1522 "{$fieldName}_relative",
1526 ['class' => 'crm-select2']
1528 $attributes = ['formatType' => 'searchDate'];
1529 $extra = ['time' => $isDateTime];
1530 $this->add('datepicker', $fieldName . $from, ts($fromLabel), $attributes, $required, $extra);
1531 $this->add('datepicker', $fieldName . $to, ts($toLabel), $attributes, $required, $extra);
1535 * Based on form action, return a string representing the api action.
1536 * Used by addField method.
1540 protected function getApiAction() {
1541 $action = $this->getAction();
1542 if ($action & (CRM_Core_Action
::UPDATE + CRM_Core_Action
::ADD
)) {
1545 if ($action & (CRM_Core_Action
::VIEW + CRM_Core_Action
::BROWSE + CRM_Core_Action
::BASIC + CRM_Core_Action
::ADVANCED + CRM_Core_Action
::PREVIEW
)) {
1548 if ($action & (CRM_Core_Action
::DELETE
)) {
1551 // If you get this exception try adding more cases above.
1552 throw new Exception("Cannot determine api action for " . get_class($this) . '.' . 'CRM_Core_Action "' . CRM_Core_Action
::description($action) . '" not recognized.');
1556 * Classes extending CRM_Core_Form should implement this method.
1559 public function getDefaultEntity() {
1560 throw new Exception("Cannot determine default entity. " . get_class($this) . " should implement getDefaultEntity().");
1564 * Classes extending CRM_Core_Form should implement this method.
1566 * TODO: Merge with CRM_Core_DAO::buildOptionsContext($context) and add validation.
1569 public function getDefaultContext() {
1570 throw new Exception("Cannot determine default context. " . get_class($this) . " should implement getDefaultContext().");
1574 * Adds a select based on field metadata.
1575 * TODO: This could be even more generic and widget type (select in this case) could also be read from metadata
1576 * Perhaps a method like $form->bind($name) which would look up all metadata for named field
1577 * @param string $name
1578 * Field name to go on the form.
1579 * @param array $props
1580 * Mix of html attributes and special properties, namely.
1581 * - entity (api entity name, can usually be inferred automatically from the form class)
1582 * - field (field name - only needed if different from name used on the form)
1583 * - option_url - path to edit this option list - usually retrieved automatically - set to NULL to disable link
1584 * - placeholder - set to NULL to disable
1586 * - context - @see CRM_Core_DAO::buildOptionsContext
1587 * @param bool $required
1588 * @throws CRM_Core_Exception
1589 * @return HTML_QuickForm_Element
1591 public function addSelect($name, $props = [], $required = FALSE) {
1592 if (!isset($props['entity'])) {
1593 $props['entity'] = $this->getDefaultEntity();
1595 if (!isset($props['field'])) {
1596 $props['field'] = strrpos($name, '[') ?
rtrim(substr($name, 1 +
strrpos($name, '[')), ']') : $name;
1598 if (!isset($props['context'])) {
1600 $props['context'] = $this->getDefaultContext();
1602 // This is not a required param, so we'll ignore if this doesn't exist.
1603 catch (Exception
$e) {
1606 // Fetch options from the api unless passed explicitly
1607 if (isset($props['options'])) {
1608 $options = $props['options'];
1611 $info = civicrm_api3($props['entity'], 'getoptions', $props);
1612 $options = $info['values'];
1614 if (!array_key_exists('placeholder', $props) && $placeholder = self
::selectOrAnyPlaceholder($props, $required)) {
1615 $props['placeholder'] = $placeholder;
1617 // Handle custom field
1618 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
1619 [, $id] = explode('_', $name);
1620 $label = $props['label'] ?? CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', 'label', $id);
1621 $gid = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', 'option_group_id', $id);
1622 if (CRM_Utils_Array
::value('context', $props) != 'search') {
1623 $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);
1628 $info = civicrm_api3($props['entity'], 'getfields');
1629 foreach ($info['values'] as $uniqueName => $fieldSpec) {
1631 $uniqueName === $props['field'] ||
1632 CRM_Utils_Array
::value('name', $fieldSpec) === $props['field'] ||
1633 in_array($props['field'], CRM_Utils_Array
::value('api.aliases', $fieldSpec, []))
1638 $label = $props['label'] ??
$fieldSpec['title'];
1639 if (CRM_Utils_Array
::value('context', $props) != 'search') {
1640 $props['data-option-edit-path'] = array_key_exists('option_url', $props) ?
$props['option_url'] : CRM_Core_PseudoConstant
::getOptionEditUrl($fieldSpec);
1643 $props['class'] = (isset($props['class']) ?
$props['class'] . ' ' : '') . "crm-select2";
1644 $props['data-api-entity'] = $props['entity'];
1645 $props['data-api-field'] = $props['field'];
1646 CRM_Utils_Array
::remove($props, 'label', 'entity', 'field', 'option_url', 'options', 'context');
1647 return $this->add('select', $name, $label, $options, $required, $props);
1651 * Handles a repeated bit supplying a placeholder for entity selection
1653 * @param string $props
1654 * The field properties, including the entity and context.
1655 * @param bool $required
1656 * If the field is required.
1657 * @param string $title
1658 * A field title, if applicable.
1660 * The placeholder text.
1662 private static function selectOrAnyPlaceholder($props, $required, $title = NULL) {
1663 if (empty($props['entity'])) {
1667 $daoToClass = CRM_Core_DAO_AllCoreTables
::daoToClass();
1668 if (array_key_exists($props['entity'], $daoToClass)) {
1669 $daoClass = $daoToClass[$props['entity']];
1670 $title = $daoClass::getEntityTitle();
1673 $title = ts('option');
1676 if (($props['context'] ??
'') == 'search' && !$required) {
1677 return ts('- any %1 -', [1 => $title]);
1679 return ts('- select %1 -', [1 => $title]);
1683 * Adds a field based on metadata.
1686 * Field name to go on the form.
1687 * @param array $props
1688 * Mix of html attributes and special properties, namely.
1689 * - entity (api entity name, can usually be inferred automatically from the form class)
1690 * - name (field name - only needed if different from name used on the form)
1691 * - option_url - path to edit this option list - usually retrieved automatically - set to NULL to disable link
1692 * - placeholder - set to NULL to disable
1694 * - context - @see CRM_Core_DAO::buildOptionsContext
1695 * @param bool $required
1696 * @param bool $legacyDate
1697 * Temporary param to facilitate the conversion of fields to use the datepicker in
1698 * a controlled way. To convert the field the jcalendar code needs to be removed from the
1699 * tpl as well. That file is intended to be EOL.
1701 * @throws \CiviCRM_API3_Exception
1702 * @throws \Exception
1704 * HTML_QuickForm_Element
1707 public function addField($name, $props = [], $required = FALSE, $legacyDate = TRUE) {
1709 if (empty($props['context'])) {
1710 $props['context'] = $this->getDefaultContext();
1712 $context = $props['context'];
1714 if (empty($props['entity'])) {
1715 $props['entity'] = $this->getDefaultEntity();
1718 if (empty($props['name'])) {
1719 $props['name'] = strrpos($name, '[') ?
rtrim(substr($name, 1 +
strrpos($name, '[')), ']') : $name;
1722 if (empty($props['action'])) {
1723 $props['action'] = $this->getApiAction();
1726 // Handle custom fields
1727 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
1728 $fieldId = (int) substr($name, 7);
1729 return CRM_Core_BAO_CustomField
::addQuickFormElement($this, $name, $fieldId, $required, $context == 'search', CRM_Utils_Array
::value('label', $props));
1732 // Core field - get metadata.
1733 $fieldSpec = civicrm_api3($props['entity'], 'getfield', $props);
1734 $fieldSpec = $fieldSpec['values'];
1735 $fieldSpecLabel = $fieldSpec['html']['label'] ?? CRM_Utils_Array
::value('title', $fieldSpec);
1736 $label = CRM_Utils_Array
::value('label', $props, $fieldSpecLabel);
1738 $widget = $props['type'] ??
$fieldSpec['html']['type'];
1739 if ($widget == 'TextArea' && $context == 'search') {
1743 $isSelect = (in_array($widget, [
1752 // Fetch options from the api unless passed explicitly.
1753 if (isset($props['options'])) {
1754 $options = $props['options'];
1757 $options = $fieldSpec['options'] ??
NULL;
1759 if ($context == 'search') {
1760 $widget = $widget == 'Select2' ?
$widget : 'Select';
1761 $props['multiple'] = CRM_Utils_Array
::value('multiple', $props, TRUE);
1764 // Add data for popup link.
1765 $canEditOptions = CRM_Core_Permission
::check('administer CiviCRM');
1766 $hasOptionUrl = !empty($props['option_url']);
1767 $optionUrlKeyIsSet = array_key_exists('option_url', $props);
1768 $shouldAdd = $context !== 'search' && $isSelect && $canEditOptions;
1770 // Only add if key is not set, or if non-empty option url is provided
1771 if (($hasOptionUrl ||
!$optionUrlKeyIsSet) && $shouldAdd) {
1772 $optionUrl = $hasOptionUrl ?
$props['option_url'] :
1773 CRM_Core_PseudoConstant
::getOptionEditUrl($fieldSpec);
1774 $props['data-option-edit-path'] = $optionUrl;
1775 $props['data-api-entity'] = $props['entity'];
1776 $props['data-api-field'] = $props['name'];
1779 $props +
= CRM_Utils_Array
::value('html', $fieldSpec, []);
1780 if (in_array($widget, ['Select', 'Select2'])
1781 && !array_key_exists('placeholder', $props)
1782 && $placeholder = self
::selectOrAnyPlaceholder($props, $required, $label)) {
1783 $props['placeholder'] = $placeholder;
1785 CRM_Utils_Array
::remove($props, 'entity', 'name', 'context', 'label', 'action', 'type', 'option_url', 'options');
1787 // TODO: refactor switch statement, to separate methods.
1793 //TODO: Autodetect ranges
1794 $props['size'] = $props['size'] ??
60;
1795 return $this->add(strtolower($widget), $name, $label, $props, $required);
1798 return $this->add('hidden', $name, NULL, $props, $required);
1801 //Set default columns and rows for textarea.
1802 $props['rows'] = $props['rows'] ??
4;
1803 $props['cols'] = $props['cols'] ??
60;
1804 if (empty($props['maxlength']) && isset($fieldSpec['length'])) {
1805 $props['maxlength'] = $fieldSpec['length'];
1807 return $this->add('textarea', $name, $label, $props, $required);
1810 // This is a white list for fields that have been tested with
1811 // date picker. We should be able to remove the other
1813 //TODO: add range support
1814 //TODO: Add date formats
1815 //TODO: Add javascript template for dates.
1816 return $this->addDate($name, $label, $required, $props);
1819 $fieldSpec = CRM_Utils_Date
::addDateMetadataToField($fieldSpec, $fieldSpec);
1820 $attributes = ['format' => $fieldSpec['date_format']];
1821 return $this->add('datepicker', $name, $label, $attributes, $required, $fieldSpec['datepicker']['extra']);
1825 $separator = $props['separator'] ??
NULL;
1826 unset($props['separator']);
1827 if (!isset($props['allowClear'])) {
1828 $props['allowClear'] = !$required;
1830 return $this->addRadio($name, $label, $options, $props, $separator, $required);
1834 'required' => $required,
1836 'multiple' => $context == 'search',
1838 return $this->addChainSelect($name, $props);
1842 $props['class'] = CRM_Utils_Array
::value('class', $props, 'big') . ' crm-select2';
1843 // TODO: Add and/or option for fields that store multiple values
1844 return $this->add(strtolower($widget), $name, $label, $options, $required, $props);
1846 case 'CheckBoxGroup':
1847 return $this->addCheckBox($name, $label, array_flip($options), $required, $props);
1850 return $this->addRadio($name, $label, $options, $props, NULL, $required);
1853 if ($context === 'search') {
1854 $this->addYesNo($name, $label, TRUE, FALSE, $props);
1857 $text = $props['text'] ??
NULL;
1858 unset($props['text']);
1859 return $this->addElement('checkbox', $name, $label, $text, $props);
1861 //add support for 'Advcheckbox' field
1863 $text = $props['text'] ??
NULL;
1864 unset($props['text']);
1865 return $this->addElement('advcheckbox', $name, $label, $text, $props);
1868 // We should not build upload file in search mode.
1869 if ($context == 'search') {
1872 $file = $this->add('file', $name, $label, $props, $required);
1873 $this->addUploadElement($name);
1876 case 'RichTextEditor':
1877 return $this->add('wysiwyg', $name, $label, $props, $required);
1880 return $this->addEntityRef($name, $label, $props, $required);
1883 $props['size'] = $props['size'] ??
60;
1884 return $this->add('password', $name, $label, $props, $required);
1886 // Check datatypes of fields
1890 //case read only fields
1892 throw new Exception("Unsupported html-element " . $widget);
1897 * Add a widget for selecting/editing/creating/copying a profile form
1899 * @param string $name
1900 * HTML form-element name.
1901 * @param string $label
1903 * @param string $allowCoreTypes
1904 * Only present a UFGroup if its group_type includes a subset of $allowCoreTypes; e.g. 'Individual', 'Activity'.
1905 * @param string $allowSubTypes
1906 * Only present a UFGroup if its group_type is compatible with $allowSubypes.
1907 * @param array $entities
1908 * @param bool $default
1910 * @param string $usedFor
1912 public function addProfileSelector($name, $label, $allowCoreTypes, $allowSubTypes, $entities, $default = FALSE, $usedFor = NULL) {
1914 // FIXME: Instead of adhoc serialization, use a single json_encode()
1915 CRM_UF_Page_ProfileEditor
::registerProfileScripts();
1916 CRM_UF_Page_ProfileEditor
::registerSchemas(CRM_Utils_Array
::collect('entity_type', $entities));
1917 $this->add('text', $name, $label, [
1918 'class' => 'crm-profile-selector',
1919 // Note: client treats ';;' as equivalent to \0, and ';;' works better in HTML
1920 'data-group-type' => CRM_Core_BAO_UFGroup
::encodeGroupType($allowCoreTypes, $allowSubTypes, ';;'),
1921 'data-entities' => json_encode($entities),
1923 'data-default' => $default,
1924 'data-usedfor' => json_encode($usedFor),
1931 public function getRootTitle() {
1938 public function getCompleteTitle() {
1939 return $this->getRootTitle() . $this->getTitle();
1943 * @return CRM_Core_Smarty
1945 public static function &getTemplate() {
1946 return self
::$_template;
1950 * @param string[]|string $elementName
1952 public function addUploadElement($elementName) {
1953 $uploadNames = $this->get('uploadNames');
1954 if (!$uploadNames) {
1957 if (is_array($elementName)) {
1958 foreach ($elementName as $name) {
1959 if (!in_array($name, $uploadNames)) {
1960 $uploadNames[] = $name;
1965 if (!in_array($elementName, $uploadNames)) {
1966 $uploadNames[] = $elementName;
1969 $this->set('uploadNames', $uploadNames);
1971 $config = CRM_Core_Config
::singleton();
1972 if (!empty($uploadNames)) {
1973 $this->controller
->addUploadAction($config->customFileUploadDir
, $uploadNames);
1978 * @param string $name
1982 public function getVar($name) {
1983 return $this->$name ??
NULL;
1987 * @param string $name
1988 * @param mixed $value
1990 public function setVar($name, $value) {
1991 $this->$name = $value;
1998 * Use $this->add('datepicker', ...) instead.
2000 * @param string $name
2001 * Name of the element.
2002 * @param string $label
2003 * Label of the element.
2004 * @param bool $required
2006 * @param array $attributes
2009 public function addDate($name, $label, $required = FALSE, $attributes = NULL) {
2010 if (!empty($attributes['formatType'])) {
2011 // get actual format
2012 $params = ['name' => $attributes['formatType']];
2015 // cache date information
2017 $key = "dateFormat_" . str_replace(' ', '_', $attributes['formatType']);
2018 if (empty($dateFormat[$key])) {
2019 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
2020 $dateFormat[$key] = $values;
2023 $values = $dateFormat[$key];
2026 if ($values['date_format']) {
2027 $attributes['format'] = $values['date_format'];
2030 if (!empty($values['time_format'])) {
2031 $attributes['timeFormat'] = $values['time_format'];
2033 $attributes['startOffset'] = $values['start'];
2034 $attributes['endOffset'] = $values['end'];
2037 $config = CRM_Core_Config
::singleton();
2038 if (empty($attributes['format'])) {
2039 $attributes['format'] = $config->dateInputFormat
;
2042 if (!isset($attributes['startOffset'])) {
2043 $attributes['startOffset'] = 10;
2046 if (!isset($attributes['endOffset'])) {
2047 $attributes['endOffset'] = 10;
2050 $this->add('text', $name, $label, $attributes);
2052 if (!empty($attributes['addTime']) ||
!empty($attributes['timeFormat'])) {
2054 if (!isset($attributes['timeFormat'])) {
2055 $timeFormat = $config->timeInputFormat
;
2058 $timeFormat = $attributes['timeFormat'];
2061 // 1 - 12 hours and 2 - 24 hours, but for jquery widget it is 0 and 1 respectively
2063 $show24Hours = TRUE;
2064 if ($timeFormat == 1) {
2065 $show24Hours = FALSE;
2068 //CRM-6664 -we are having time element name
2069 //in either flat string or an array format.
2070 $elementName = $name . '_time';
2071 if (substr($name, -1) == ']') {
2072 $elementName = substr($name, 0, strlen($name) - 1) . '_time]';
2075 $this->add('text', $elementName, ts('Time'), ['timeFormat' => $show24Hours]);
2080 $this->addRule($name, ts('Please select %1', [1 => $label]), 'required');
2081 if (!empty($attributes['addTime']) && !empty($attributes['addTimeRequired'])) {
2082 $this->addRule($elementName, ts('Please enter a time.'), 'required');
2088 * Function that will add date and time.
2091 * Use $this->add('datepicker', ...) instead.
2093 * @param string $name
2094 * @param string $label
2095 * @param bool $required
2096 * @param array $attributes
2098 public function addDateTime($name, $label, $required = FALSE, $attributes = NULL) {
2099 $addTime = ['addTime' => TRUE];
2100 if (is_array($attributes)) {
2101 $attributes = array_merge($attributes, $addTime);
2104 $attributes = $addTime;
2107 $this->addDate($name, $label, $required, $attributes);
2111 * Add a currency and money element to the form.
2113 * @param string $name
2114 * @param string $label
2115 * @param bool $required
2116 * @param array $attributes
2117 * @param bool $addCurrency
2118 * @param string $currencyName
2119 * @param string $defaultCurrency
2120 * @param bool $freezeCurrency
2122 * @return \HTML_QuickForm_Element
2124 public function addMoney(
2129 $addCurrency = TRUE,
2130 $currencyName = 'currency',
2131 $defaultCurrency = NULL,
2132 $freezeCurrency = FALSE
2134 $element = $this->add('text', $name, $label, $attributes, $required);
2135 $this->addRule($name, ts('Please enter a valid amount.'), 'money');
2138 $ele = $this->addCurrency($currencyName, NULL, TRUE, $defaultCurrency, $freezeCurrency);
2145 * Add currency element to the form.
2147 * @param string $name
2148 * @param string $label
2149 * @param bool $required
2150 * @param string $defaultCurrency
2151 * @param bool $freezeCurrency
2152 * @param bool $setDefaultCurrency
2154 public function addCurrency(
2158 $defaultCurrency = NULL,
2159 $freezeCurrency = FALSE,
2160 $setDefaultCurrency = TRUE
2162 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
2163 if (!empty($defaultCurrency) && !array_key_exists($defaultCurrency, $currencies)) {
2164 Civi
::log()->warning('addCurrency: Currency ' . $defaultCurrency . ' is disabled but still in use!');
2165 $currencies[$defaultCurrency] = $defaultCurrency;
2167 $options = ['class' => 'crm-select2 eight'];
2169 $currencies = ['' => ''] +
$currencies;
2170 $options['placeholder'] = ts('- none -');
2172 $ele = $this->add('select', $name, $label, $currencies, $required, $options);
2173 if ($freezeCurrency) {
2176 if (!$defaultCurrency) {
2177 $config = CRM_Core_Config
::singleton();
2178 $defaultCurrency = $config->defaultCurrency
;
2180 // In some case, setting currency field by default might override the default value
2181 // as encountered in CRM-20527 for batch data entry
2182 if ($setDefaultCurrency) {
2183 $this->setDefaults([$name => $defaultCurrency]);
2188 * Create a single or multiple entity ref field.
2189 * @param string $name
2190 * @param string $label
2191 * @param array $props
2192 * Mix of html and widget properties, including:.
2193 * - select - params to give to select2 widget
2194 * - entity - defaults to Contact
2195 * - create - can the user create a new entity on-the-fly?
2196 * Set to TRUE if entity is contact and you want the default profiles,
2197 * or pass in your own set of links. @see CRM_Campaign_BAO_Campaign::getEntityRefCreateLinks for format
2198 * note that permissions are checked automatically
2199 * - api - array of settings for the getlist api wrapper
2200 * note that it accepts a 'params' setting which will be passed to the underlying api
2201 * - placeholder - string
2203 * - class, etc. - other html properties
2204 * @param bool $required
2206 * @return HTML_QuickForm_Element
2208 public function addEntityRef($name, $label = '', $props = [], $required = FALSE) {
2209 // Default properties
2210 $props['api'] = CRM_Utils_Array
::value('api', $props, []);
2211 $props['entity'] = CRM_Core_DAO_AllCoreTables
::convertEntityNameToCamel($props['entity'] ??
'Contact');
2212 $props['class'] = ltrim(($props['class'] ??
'') . ' crm-form-entityref');
2214 if (array_key_exists('create', $props) && empty($props['create'])) {
2215 unset($props['create']);
2218 $props['placeholder'] = $props['placeholder'] ?? self
::selectOrAnyPlaceholder($props, $required);
2221 if (!empty($props['multiple'])) {
2222 $defaults['multiple'] = TRUE;
2224 $props['select'] = CRM_Utils_Array
::value('select', $props, []) +
$defaults;
2226 $this->formatReferenceFieldAttributes($props, get_class($this));
2227 return $this->add('text', $name, $label, $props, $required);
2231 * @param array $props
2232 * @param string $formName
2234 private function formatReferenceFieldAttributes(&$props, $formName) {
2235 CRM_Utils_Hook
::alterEntityRefParams($props, $formName);
2236 $props['data-select-params'] = json_encode($props['select']);
2237 $props['data-api-params'] = $props['api'] ?
json_encode($props['api']) : NULL;
2238 $props['data-api-entity'] = $props['entity'];
2239 if (!empty($props['create'])) {
2240 $props['data-create-links'] = json_encode($props['create']);
2242 CRM_Utils_Array
::remove($props, 'multiple', 'select', 'api', 'entity', 'create');
2246 * @param $elementName
2248 public function removeFileRequiredRules($elementName) {
2249 $this->_required
= array_diff($this->_required
, [$elementName]);
2250 if (isset($this->_rules
[$elementName])) {
2251 foreach ($this->_rules
[$elementName] as $index => $ruleInfo) {
2252 if ($ruleInfo['type'] == 'uploadedfile') {
2253 unset($this->_rules
[$elementName][$index]);
2256 if (empty($this->_rules
[$elementName])) {
2257 unset($this->_rules
[$elementName]);
2263 * Function that can be defined in Form to override or.
2264 * perform specific action on cancel action
2266 public function cancelAction() {
2270 * Helper function to verify that required fields have been filled.
2272 * Typically called within the scope of a FormRule function
2274 * @param array $fields
2275 * @param array $values
2276 * @param array $errors
2278 public static function validateMandatoryFields($fields, $values, &$errors) {
2279 foreach ($fields as $name => $fld) {
2280 if (!empty($fld['is_required']) && CRM_Utils_System
::isNull(CRM_Utils_Array
::value($name, $values))) {
2281 $errors[$name] = ts('%1 is a required field.', [1 => $fld['title']]);
2287 * Get contact if for a form object. Prioritise
2288 * - cid in URL if 0 (on behalf on someoneelse)
2289 * (@todo consider setting a variable if onbehalf for clarity of downstream 'if's
2290 * - logged in user id if it matches the one in the cid in the URL
2291 * - contact id validated from a checksum from a checksum
2292 * - cid from the url if the caller has ACL permission to view
2293 * - fallback is logged in user (or ? NULL if no logged in user) (@todo wouldn't 0 be more intuitive?)
2297 protected function setContactID() {
2298 $tempID = CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
2299 if (isset($this->_params
) && !empty($this->_params
['select_contact_id'])) {
2300 $tempID = $this->_params
['select_contact_id'];
2302 if (isset($this->_params
, $this->_params
[0]) && !empty($this->_params
[0]['select_contact_id'])) {
2303 // event form stores as an indexed array, contribution form not so much...
2304 $tempID = $this->_params
[0]['select_contact_id'];
2307 // force to ignore the authenticated user
2308 if ($tempID === '0' ||
$tempID === 0) {
2309 // we set the cid on the form so that this will be retained for the Confirm page
2310 // in the multi-page form & prevent us returning the $userID when this is called
2312 // we don't really need to set it when $tempID is set because the params have that stored
2313 $this->set('cid', 0);
2314 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $tempID]);
2315 return (int) $tempID;
2318 $userID = CRM_Core_Session
::getLoggedInContactID();
2320 if (!is_null($tempID) && $tempID === $userID) {
2321 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $tempID]);
2322 return (int) $userID;
2325 //check if this is a checksum authentication
2326 $userChecksum = CRM_Utils_Request
::retrieve('cs', 'String', $this);
2327 if ($userChecksum) {
2328 //check for anonymous user.
2329 $validUser = CRM_Contact_BAO_Contact_Utils
::validChecksum($tempID, $userChecksum);
2331 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $tempID]);
2332 CRM_Core_Resources
::singleton()->addVars('coreForm', ['checksum' => $userChecksum]);
2336 // check if user has permission, CRM-12062
2337 elseif ($tempID && CRM_Contact_BAO_Contact_Permission
::allow($tempID)) {
2338 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $tempID]);
2341 if (is_numeric($userID)) {
2342 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $userID]);
2344 return is_numeric($userID) ?
$userID : NULL;
2348 * Get the contact id that the form is being submitted for.
2352 public function getContactID() {
2353 return $this->setContactID();
2357 * Get the contact id of the logged in user.
2362 public function getLoggedInUserContactID() {
2363 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_Session::getLoggedInContactID()');
2364 // check if the user is logged in and has a contact ID
2365 $session = CRM_Core_Session
::singleton();
2366 return $session->get('userID') ?
(int) $session->get('userID') : FALSE;
2370 * Add autoselector field -if user has permission to view contacts
2371 * If adding this to a form you also need to add to the tpl e.g
2373 * {if !empty($selectable)}
2374 * <div class="crm-summary-row">
2375 * <div class="crm-label">{$form.select_contact.label}</div>
2376 * <div class="crm-content">
2377 * {$form.select_contact.html}
2382 * @param array $profiles
2383 * Ids of profiles that are on the form (to be autofilled).
2384 * @param array $autoCompleteField
2388 * - url (for ajax lookup)
2390 * @throws \CRM_Core_Exception
2391 * @todo add data attributes so we can deal with multiple instances on a form
2393 public function addAutoSelector($profiles = [], $autoCompleteField = []) {
2394 $autoCompleteField = array_merge([
2395 'id_field' => 'select_contact_id',
2396 'placeholder' => ts('Select someone else ...'),
2397 'show_hide' => TRUE,
2398 'api' => ['params' => ['contact_type' => 'Individual']],
2399 ], $autoCompleteField);
2401 if ($this->canUseAjaxContactLookups()) {
2402 $this->assign('selectable', $autoCompleteField['id_field']);
2403 $this->addEntityRef($autoCompleteField['id_field'], NULL, [
2404 'placeholder' => $autoCompleteField['placeholder'],
2405 'api' => $autoCompleteField['api'],
2408 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/AlternateContactSelector.js', 1, 'html-header')
2410 'form' => ['autocompletes' => $autoCompleteField],
2411 'ids' => ['profile' => $profiles],
2419 public function canUseAjaxContactLookups() {
2420 if (0 < (civicrm_api3('contact', 'getcount', ['check_permissions' => 1])) &&
2421 CRM_Core_Permission
::check([['access AJAX API', 'access CiviCRM']])
2429 * Add the options appropriate to cid = zero - ie. autocomplete
2431 * @todo there is considerable code duplication between the contribution forms & event forms. It is apparent
2432 * that small pieces of duplication are not being refactored into separate functions because their only shared parent
2433 * is this form. Inserting a class FrontEndForm.php between the contribution & event & this class would allow functions like this
2434 * and a dozen other small ones to be refactored into a shared parent with the reduction of much code duplication
2436 public function addCIDZeroOptions() {
2437 $this->assign('nocid', TRUE);
2439 if ($this->_values
['custom_pre_id']) {
2440 $profiles[] = $this->_values
['custom_pre_id'];
2442 if ($this->_values
['custom_post_id']) {
2443 $profiles = array_merge($profiles, (array) $this->_values
['custom_post_id']);
2445 $profiles[] = 'billing';
2446 if (!empty($this->_values
)) {
2447 $this->addAutoSelector($profiles);
2452 * Set default values on form for given contact (or no contact defaults)
2454 * @param mixed $profile_id
2455 * (can be id, or profile name).
2456 * @param int $contactID
2460 public function getProfileDefaults($profile_id = 'Billing', $contactID = NULL) {
2462 $defaults = civicrm_api3('profile', 'getsingle', [
2463 'profile_id' => (array) $profile_id,
2464 'contact_id' => $contactID,
2468 catch (Exception
$e) {
2469 // the try catch block gives us silent failure -not 100% sure this is a good idea
2470 // as silent failures are often worse than noisy ones
2476 * Sets form attribute.
2479 public function preventAjaxSubmit() {
2480 $this->setAttribute('data-no-ajax-submit', 'true');
2484 * Sets form attribute.
2487 public function allowAjaxSubmit() {
2488 $this->removeAttribute('data-no-ajax-submit');
2492 * Sets page title based on entity and action.
2493 * @param string $entityLabel
2495 public function setPageTitle($entityLabel) {
2496 switch ($this->_action
) {
2497 case CRM_Core_Action
::ADD
:
2498 $this->setTitle(ts('New %1', [1 => $entityLabel]));
2501 case CRM_Core_Action
::UPDATE
:
2502 $this->setTitle(ts('Edit %1', [1 => $entityLabel]));
2505 case CRM_Core_Action
::VIEW
:
2506 case CRM_Core_Action
::PREVIEW
:
2507 $this->setTitle(ts('View %1', [1 => $entityLabel]));
2510 case CRM_Core_Action
::DELETE
:
2511 $this->setTitle(ts('Delete %1', [1 => $entityLabel]));
2517 * Create a chain-select target field. All settings are optional; the defaults usually work.
2519 * @param string $elementName
2520 * @param array $settings
2522 * @return HTML_QuickForm_Element
2524 public function addChainSelect($elementName, $settings = []) {
2525 $required = $settings['required'] ??
FALSE;
2526 $label = strpos($elementName, 'rovince') ? CRM_Core_DAO_StateProvince
::getEntityTitle() : CRM_Core_DAO_County
::getEntityTitle();
2527 $props = $settings +
= [
2528 'control_field' => str_replace(['state_province', 'StateProvince', 'county', 'County'], [
2534 'data-callback' => strpos($elementName, 'rovince') ?
'civicrm/ajax/jqState' : 'civicrm/ajax/jqCounty',
2536 'data-empty-prompt' => strpos($elementName, 'rovince') ?
ts('Choose country first') : ts('Choose state first'),
2537 'data-none-prompt' => ts('- N/A -'),
2538 'multiple' => FALSE,
2539 'required' => $required,
2540 'placeholder' => ts('- select %1 -', [1 => $label]),
2542 CRM_Utils_Array
::remove($props, 'label', 'required', 'control_field', 'context');
2543 $props['class'] = (empty($props['class']) ?
'' : "{$props['class']} ") . 'crm-select2' . ($required ?
' required crm-field-required' : '');
2544 $props['data-select-prompt'] = $props['placeholder'];
2545 $props['data-name'] = $elementName;
2547 $this->_chainSelectFields
[$settings['control_field']] = $elementName;
2549 // Passing NULL instead of an array of options
2550 // CRM-15225 - normally QF will reject any selected values that are not part of the field's options, but due to a
2551 // quirk in our patched version of HTML_QuickForm_select, this doesn't happen if the options are NULL
2552 // which seems a bit dirty but it allows our dynamically-popuplated select element to function as expected.
2553 return $this->add('select', $elementName, $settings['label'], NULL, $required, $props);
2557 * Add actions menu to results form.
2559 * @param array $tasks
2561 public function addTaskMenu($tasks) {
2562 if (is_array($tasks) && !empty($tasks)) {
2563 // Set constants means this will always load with an empty value, not reloading any submitted value.
2564 // This is appropriate as it is a pseudofield.
2565 $this->setConstants(['task' => '']);
2566 $this->assign('taskMetaData', $tasks);
2567 $select = $this->add('select', 'task', NULL, ['' => ts('Actions')], FALSE, [
2568 'class' => 'crm-select2 crm-action-menu fa-check-circle-o huge crm-search-result-actions',
2571 foreach ($tasks as $key => $task) {
2573 if (isset($task['data'])) {
2574 foreach ($task['data'] as $dataKey => $dataValue) {
2575 $attributes['data-' . $dataKey] = $dataValue;
2578 $select->addOption($task['title'], $key, $attributes);
2580 if (empty($this->_actionButtonName
)) {
2581 $this->_actionButtonName
= $this->getButtonName('next', 'action');
2583 $this->assign('actionButtonName', $this->_actionButtonName
);
2584 $this->add('xbutton', $this->_actionButtonName
, ts('Go'), [
2586 'class' => 'hiddenElement crm-search-go-button',
2589 // Radio to choose "All items" or "Selected items only"
2590 $selectedRowsRadio = $this->addElement('radio', 'radio_ts', NULL, '', 'ts_sel', ['checked' => 'checked']);
2591 $allRowsRadio = $this->addElement('radio', 'radio_ts', NULL, '', 'ts_all');
2592 $this->assign('ts_sel_id', $selectedRowsRadio->_attributes
['id']);
2593 $this->assign('ts_all_id', $allRowsRadio->_attributes
['id']);
2595 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header');
2600 * Set options and attributes for chain select fields based on the controlling field's value
2602 private function preProcessChainSelectFields() {
2603 foreach ($this->_chainSelectFields
as $control => $target) {
2604 // The 'target' might get missing if extensions do removeElement() in a form hook.
2605 if ($this->elementExists($target)) {
2606 $targetField = $this->getElement($target);
2607 $targetType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ?
'county' : 'stateProvince';
2609 // If the control field is on the form, setup chain-select and dynamically populate options
2610 if ($this->elementExists($control)) {
2611 $controlField = $this->getElement($control);
2612 $controlType = $targetType == 'county' ?
'stateProvince' : 'country';
2614 $targetField->setAttribute('class', $targetField->getAttribute('class') . ' crm-chain-select-target');
2616 $css = (string) $controlField->getAttribute('class');
2617 $controlField->updateAttributes([
2618 'class' => ($css ?
"$css " : 'crm-select2 ') . 'crm-chain-select-control',
2619 'data-target' => $target,
2621 $controlValue = $controlField->getValue();
2622 if ($controlValue) {
2623 $options = CRM_Core_BAO_Location
::getChainSelectValues($controlValue, $controlType, TRUE);
2625 $targetField->setAttribute('placeholder', $targetField->getAttribute('data-none-prompt'));
2629 $targetField->setAttribute('placeholder', $targetField->getAttribute('data-empty-prompt'));
2630 $targetField->setAttribute('disabled', 'disabled');
2633 // Control field not present - fall back to loading default options
2635 $options = CRM_Core_PseudoConstant
::$targetType();
2637 if (!$targetField->getAttribute('multiple')) {
2638 $options = ['' => $targetField->getAttribute('placeholder')] +
$options;
2639 $targetField->removeAttribute('placeholder');
2641 $targetField->_options
= [];
2642 $targetField->loadArray($options);
2648 * Validate country / state / county match and suppress unwanted "required" errors
2650 private function validateChainSelectFields() {
2651 foreach ($this->_chainSelectFields
as $control => $target) {
2652 if ($this->elementExists($control) && $this->elementExists($target)) {
2653 $controlValue = (array) $this->getElementValue($control);
2654 $targetField = $this->getElement($target);
2655 $controlType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ?
'stateProvince' : 'country';
2656 $targetValue = array_filter((array) $targetField->getValue());
2657 if ($targetValue ||
$this->getElementError($target)) {
2658 $options = CRM_Core_BAO_Location
::getChainSelectValues($controlValue, $controlType, TRUE);
2660 if (!array_intersect($targetValue, array_keys($options))) {
2661 $this->setElementError($target, $controlType == 'country' ?
ts('State/Province does not match the selected Country') : ts('County does not match the selected State/Province'));
2664 // Suppress "required" error for field if it has no options
2665 elseif (!$options) {
2666 $this->setElementError($target, NULL);
2674 * Assign billing name to the template.
2676 * @param array $params
2677 * Form input params, default to $this->_params.
2681 public function assignBillingName($params = []) {
2683 if (empty($params)) {
2684 $params = $this->_params
;
2686 if (!empty($params['billing_first_name'])) {
2687 $name = $params['billing_first_name'];
2690 if (!empty($params['billing_middle_name'])) {
2691 $name .= " {$params['billing_middle_name']}";
2694 if (!empty($params['billing_last_name'])) {
2695 $name .= " {$params['billing_last_name']}";
2697 $name = trim($name);
2698 $this->assign('billingName', $name);
2703 * Get the currency for the form.
2705 * @todo this should be overriden on the forms rather than having this
2706 * historic, possible handling in here. As we clean that up we should
2707 * add deprecation notices into here.
2709 * @param array $submittedValues
2710 * Array allowed so forms inheriting this class do not break.
2711 * Ideally we would make a clear standard around how submitted values
2712 * are stored (is $this->_values consistently doing that?).
2716 public function getCurrency($submittedValues = []) {
2717 $currency = $this->_values
['currency'] ??
NULL;
2718 // For event forms, currency is in a different spot
2719 if (empty($currency)) {
2720 $currency = CRM_Utils_Array
::value('currency', CRM_Utils_Array
::value('event', $this->_values
));
2722 if (empty($currency)) {
2723 $currency = CRM_Utils_Request
::retrieveValue('currency', 'String');
2725 // @todo If empty there is a problem - we should probably put in a deprecation notice
2726 // to warn if that seems to be happening.
2731 * Is the form in view or edit mode.
2733 * The 'addField' function relies on the form action being one of a set list
2734 * of actions. Checking for these allows for an early return.
2738 protected function isFormInViewOrEditMode() {
2739 return $this->isFormInViewMode() ||
$this->isFormInEditMode();
2743 * Is the form in edit mode.
2745 * Helper function, notably for extensions implementing the buildForm hook,
2746 * so that they can return early.
2750 public function isFormInEditMode() {
2751 return in_array($this->_action
, [
2752 CRM_Core_Action
::UPDATE
,
2753 CRM_Core_Action
::ADD
,
2754 CRM_Core_Action
::BROWSE
,
2755 CRM_Core_Action
::BASIC
,
2756 CRM_Core_Action
::ADVANCED
,
2757 CRM_Core_Action
::PREVIEW
,
2762 * Is the form in view mode.
2764 * Helper function, notably for extensions implementing the buildForm hook,
2765 * so that they can return early.
2769 public function isFormInViewMode() {
2770 return $this->_action
== CRM_Core_Action
::VIEW
;
2774 * Set the active tab
2776 * @param string $default
2778 * @throws \CRM_Core_Exception
2780 public function setSelectedChild($default = NULL) {
2781 $selectedChild = CRM_Utils_Request
::retrieve('selectedChild', 'Alphanumeric', $this, FALSE, $default);
2782 if (!empty($selectedChild)) {
2783 $this->set('selectedChild', $selectedChild);
2784 $this->assign('selectedChild', $selectedChild);
2785 Civi
::resources()->addSetting(['tabSettings' => ['active' => $selectedChild]]);
2790 * Get the contact if from the url, using the checksum or the cid if it is the logged in user.
2792 * This function returns the user being validated. It is not intended to get another user
2793 * they have permission to (setContactID does do that) and can be used to check if the user is
2794 * accessing their own record.
2797 * @throws \CRM_Core_Exception
2799 protected function getContactIDIfAccessingOwnRecord() {
2800 $contactID = (int) CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
2804 if ($contactID === CRM_Core_Session
::getLoggedInContactID()) {
2807 $userChecksum = CRM_Utils_Request
::retrieve('cs', 'String', $this);
2808 return CRM_Contact_BAO_Contact_Utils
::validChecksum($contactID, $userChecksum) ?
$contactID : FALSE;
2812 * Get values submitted by the user.
2814 * These values have been validated against the fields added to the form.
2815 * https://pear.php.net/manual/en/package.html.html-quickform.html-quickform.exportvalues.php
2817 * @param string $fieldName
2819 * @return mixed|null
2821 public function getSubmittedValue(string $fieldName) {
2822 if (empty($this->exportedValues
)) {
2823 $this->exportedValues
= $this->controller
->exportValues($this->_name
);
2825 $value = $this->exportedValues
[$fieldName] ??
NULL;
2826 if (in_array($fieldName, $this->submittableMoneyFields
, TRUE)) {
2827 return CRM_Utils_Rule
::cleanMoney($value);
2833 * Get the active UFGroups (profiles) on this form
2834 * Many forms load one or more UFGroups (profiles).
2835 * This provides a standard function to retrieve the IDs of those profiles from the form
2836 * so that you can implement things such as "is is_captcha field set on any of the active profiles on this form?"
2838 * NOT SUPPORTED FOR USE OUTSIDE CORE EXTENSIONS - Added for reCAPTCHA core extension.
2842 public function getUFGroupIDs() {