3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * This is our base form. It is part of the Form/Controller/StateMachine
30 * trifecta. Each form is associated with a specific state in the state
31 * machine. Each form can also operate in various modes
34 * @copyright CiviCRM LLC (c) 2004-2019
37 require_once 'HTML/QuickForm/Page.php';
42 class CRM_Core_Form
extends HTML_QuickForm_Page
{
45 * The state object that this form belongs to
51 * The name of this form
57 * The title of this form
60 protected $_title = NULL;
63 * The default values for the form.
67 public $_defaults = [];
70 * (QUASI-PROTECTED) The options passed into this form
72 * This field should marked `protected` and is not generally
73 * intended for external callers, but some edge-cases do use it.
77 public $_options = NULL;
80 * (QUASI-PROTECTED) The mode of operation for this form
82 * This field should marked `protected` and is not generally
83 * intended for external callers, but some edge-cases do use it.
90 * Available payment processors.
92 * As part of trying to consolidate various payment pages we store processors here & have functions
93 * at this level to manage them.
96 * An array of payment processor details with objects loaded in the 'object' field.
98 protected $_paymentProcessors;
101 * Available payment processors (IDS).
103 * As part of trying to consolidate various payment pages we store processors here & have functions
104 * at this level to manage them. An alternative would be to have a separate Form that is inherited
105 * by all forms that allow payment processing.
108 * An array of the IDS available on this form.
110 public $_paymentProcessorIDs;
113 * Default or selected processor id.
115 * As part of trying to consolidate various payment pages we store processors here & have functions
116 * at this level to manage them. An alternative would be to have a separate Form that is inherited
117 * by all forms that allow payment processing.
121 protected $_paymentProcessorID;
124 * Is pay later enabled for the form.
126 * As part of trying to consolidate various payment pages we store processors here & have functions
127 * at this level to manage them. An alternative would be to have a separate Form that is inherited
128 * by all forms that allow payment processing.
132 protected $_is_pay_later_enabled;
135 * The renderer used for this form
139 protected $_renderer;
142 * An array to hold a list of datefields on the form
143 * so that they can be converted to ISO in a consistent manner
147 * e.g on a form declare $_dateFields = array(
148 * 'receive_date' => array('default' => 'now'),
150 * then in postProcess call $this->convertDateFieldsToMySQL($formValues)
151 * to have the time field re-incorporated into the field & 'now' set if
152 * no value has been passed in
154 protected $_dateFields = [];
157 * Cache the smarty template for efficiency reasons
159 * @var CRM_Core_Smarty
161 static protected $_template;
164 * Indicate if this form should warn users of unsaved changes
167 protected $unsavedChangesWarn;
170 * What to return to the client if in ajax mode (snippet=json)
174 public $ajaxResponse = [];
177 * Url path used to reach this page
181 public $urlPath = [];
184 * Context of the form being loaded.
195 public function getContext() {
196 return $this->context
;
200 * Set context variable.
202 public function setContext() {
203 $this->context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
207 * @var CRM_Core_Controller
212 * Constants for attributes for various form elements
213 * attempt to standardize on the number of variations that we
214 * use of the below form elements
218 const ATTR_SPACING
= ' ';
221 * All checkboxes are defined with a common prefix. This allows us to
222 * have the same javascript to check / clear all the checkboxes etc
223 * If u have multiple groups of checkboxes, you will need to give them different
224 * ids to avoid potential name collision
228 const CB_PREFIX
= 'mark_x_', CB_PREFIY
= 'mark_y_', CB_PREFIZ
= 'mark_z_', CB_PREFIX_LEN
= 7;
232 * @internal to keep track of chain-select fields
234 private $_chainSelectFields = [];
237 * Extra input types we support via the "add" method
240 public static $html5Types = [
248 * Constructor for the basic form page.
250 * We should not use QuickForm directly. This class provides a lot
251 * of default convenient functions, rules and buttons
253 * @param object $state
254 * State associated with this form.
255 * @param \const|\enum|int $action The mode the form is operating in (None/Create/View/Update/Delete)
256 * @param string $method
257 * The type of http method used (GET/POST).
258 * @param string $name
259 * The name of the form if different from class name.
261 * @return \CRM_Core_Form
263 public function __construct(
265 $action = CRM_Core_Action
::NONE
,
271 $this->_name
= $name;
274 // CRM-15153 - FIXME this name translates to a DOM id and is not always unique!
275 $this->_name
= CRM_Utils_String
::getClassName(CRM_Utils_System
::getClassName($this));
278 parent
::__construct($this->_name
, $method);
280 $this->_state
=& $state;
282 $this->_state
->setName($this->_name
);
284 $this->_action
= (int) $action;
286 $this->registerRules();
288 // let the constructor initialize this, should happen only once
289 if (!isset(self
::$_template)) {
290 self
::$_template = CRM_Core_Smarty
::singleton();
292 // Workaround for CRM-15153 - give each form a reasonably unique css class
293 $this->addClass(CRM_Utils_System
::getClassName($this));
295 $this->assign('snippet', CRM_Utils_Array
::value('snippet', $_GET));
296 $this->setTranslatedFields();
300 * Set translated fields.
302 * This function is called from the class constructor, allowing us to set
303 * fields on the class that can't be set as properties due to need for
304 * translation or other non-input specific handling.
306 protected function setTranslatedFields() {}
309 * Add one or more css classes to the form.
311 * @param string $className
313 public function addClass($className) {
314 $classes = $this->getAttribute('class');
315 $this->setAttribute('class', ($classes ?
"$classes " : '') . $className);
319 * Register all the standard rules that most forms potentially use.
321 public function registerRules() {
351 foreach ($rules as $rule) {
352 $this->registerRule($rule, 'callback', $rule, 'CRM_Utils_Rule');
357 * Simple easy to use wrapper around addElement.
359 * Deal with simple validation rules.
361 * @param string $type
362 * @param string $name
363 * @param string $label
364 * @param string|array $attributes (options for select elements)
365 * @param bool $required
366 * @param array $extra
367 * (attributes for select elements).
368 * For datepicker elements this is consistent with the data
369 * from CRM_Utils_Date::getDatePickerExtra
371 * @return HTML_QuickForm_Element
372 * Could be an error object
374 public function &add(
375 $type, $name, $label = '',
376 $attributes = '', $required = FALSE, $extra = NULL
378 // Fudge some extra types that quickform doesn't support
380 if ($type == 'wysiwyg' ||
in_array($type, self
::$html5Types)) {
381 $attributes = ($attributes ?
$attributes : []) +
['class' => ''];
382 $attributes['class'] = ltrim($attributes['class'] . " crm-form-$type");
383 if ($type == 'wysiwyg' && isset($attributes['preset'])) {
384 $attributes['data-preset'] = $attributes['preset'];
385 unset($attributes['preset']);
387 $type = $type == 'wysiwyg' ?
'textarea' : 'text';
389 // Like select but accepts rich array data (with nesting, colors, icons, etc) as option list.
390 if ($inputType == 'select2') {
392 $options = $attributes;
393 $attributes = ($extra ?
$extra : []) +
['class' => ''];
394 $attributes['class'] = ltrim($attributes['class'] . " crm-select2 crm-form-select2");
395 $attributes['data-select-params'] = json_encode(['data' => $options, 'multiple' => !empty($attributes['multiple'])]);
396 unset($attributes['multiple']);
399 // @see http://wiki.civicrm.org/confluence/display/CRMDOC/crmDatepicker
400 if ($type == 'datepicker') {
401 $attributes = ($attributes ?
$attributes : []);
402 $attributes['data-crm-datepicker'] = json_encode((array) $extra);
403 if (!empty($attributes['aria-label']) ||
$label) {
404 $attributes['aria-label'] = CRM_Utils_Array
::value('aria-label', $attributes, $label);
408 if ($type == 'select' && is_array($extra)) {
409 // Normalize this property
410 if (!empty($extra['multiple'])) {
411 $extra['multiple'] = 'multiple';
414 unset($extra['multiple']);
416 unset($extra['size'], $extra['maxlength']);
417 // Add placeholder option for select
418 if (isset($extra['placeholder'])) {
419 if ($extra['placeholder'] === TRUE) {
420 $extra['placeholder'] = $required ?
ts('- select -') : ts('- none -');
422 if (($extra['placeholder'] ||
$extra['placeholder'] === '') && empty($extra['multiple']) && is_array($attributes) && !isset($attributes[''])) {
423 $attributes = ['' => $extra['placeholder']] +
$attributes;
427 $element = $this->addElement($type, $name, $label, $attributes, $extra);
428 if (HTML_QuickForm
::isError($element)) {
429 CRM_Core_Error
::fatal(HTML_QuickForm
::errorMessage($element));
432 if ($inputType == 'color') {
433 $this->addRule($name, ts('%1 must contain a color value e.g. #ffffff.', [1 => $label]), 'regex', '/#[0-9a-fA-F]{6}/');
437 if ($type == 'file') {
438 $error = $this->addRule($name, ts('%1 is a required field.', [1 => $label]), 'uploadedfile');
441 $error = $this->addRule($name, ts('%1 is a required field.', [1 => $label]), 'required');
443 if (HTML_QuickForm
::isError($error)) {
444 CRM_Core_Error
::fatal(HTML_QuickForm
::errorMessage($element));
448 // Add context for the editing of option groups
449 if (isset($extra['option_context'])) {
450 $context = json_encode($extra['option_context']);
451 $element->setAttribute('data-option-edit-context', $context);
460 * This is called before buildForm. Any pre-processing that
461 * needs to be done for buildForm should be done here.
463 * This is a virtual function and should be redefined if needed.
465 public function preProcess() {
469 * Called after the form is validated.
471 * Any processing of form state etc should be done in this function.
472 * Typically all processing associated with a form should be done
473 * here and relevant state should be stored in the session
475 * This is a virtual function and should be redefined if needed
477 public function postProcess() {
481 * Main process wrapper.
483 * Implemented so that we can call all the hook functions.
485 * @param bool $allowAjax
486 * FIXME: This feels kind of hackish, ideally we would take the json-related code from this function.
487 * and bury it deeper down in the controller
489 public function mainProcess($allowAjax = TRUE) {
490 $this->postProcess();
491 $this->postProcessHook();
493 // Respond with JSON if in AJAX context (also support legacy value '6')
494 if ($allowAjax && !empty($_REQUEST['snippet']) && in_array($_REQUEST['snippet'], [
495 CRM_Core_Smarty
::PRINT_JSON
,
498 $this->ajaxResponse
['buttonName'] = str_replace('_qf_' . $this->getAttribute('id') . '_', '', $this->controller
->getButtonName());
499 $this->ajaxResponse
['action'] = $this->_action
;
500 if (isset($this->_id
) ||
isset($this->id
)) {
501 $this->ajaxResponse
['id'] = isset($this->id
) ?
$this->id
: $this->_id
;
503 CRM_Core_Page_AJAX
::returnJsonResponse($this->ajaxResponse
);
508 * The postProcess hook is typically called by the framework.
510 * However in a few cases, the form exits or redirects early in which
511 * case it needs to call this function so other modules can do the needful
512 * Calling this function directly should be avoided if possible. In general a
513 * better way is to do setUserContext so the framework does the redirect
515 public function postProcessHook() {
516 CRM_Utils_Hook
::postProcess(get_class($this), $this);
520 * This virtual function is used to build the form.
522 * It replaces the buildForm associated with QuickForm_Page. This allows us to put
523 * preProcess in front of the actual form building routine
525 public function buildQuickForm() {
529 * This virtual function is used to set the default values of various form elements.
532 * reference to the array of default values
534 public function setDefaultValues() {
539 * This is a virtual function that adds group and global rules to the form.
541 * Keeping it distinct from the form to keep code small
542 * and localized in the form building code
544 public function addRules() {
548 * Performs the server side validation.
551 * true if no error found
552 * @throws HTML_QuickForm_Error
554 public function validate() {
555 $error = parent
::validate();
557 $this->validateChainSelectFields();
561 CRM_Utils_Hook
::validateForm(
563 $this->_submitValues
,
569 if (!empty($hookErrors)) {
570 $this->_errors +
= $hookErrors;
573 return (0 == count($this->_errors
));
577 * Core function that builds the form.
579 * We redefine this function here and expect all CRM forms to build their form in the function
582 public function buildForm() {
583 $this->_formBuilt
= TRUE;
587 CRM_Utils_Hook
::preProcess(get_class($this), $this);
589 $this->assign('translatePermission', CRM_Core_Permission
::check('translate CiviCRM'));
592 $this->controller
->_key
&&
593 $this->controller
->_generateQFKey
595 $this->addElement('hidden', 'qfKey', $this->controller
->_key
);
596 $this->assign('qfKey', $this->controller
->_key
);
600 // _generateQFKey suppresses the qfKey generation on form snippets that
601 // are part of other forms, hence we use that to avoid adding entryURL
602 if ($this->controller
->_generateQFKey
&& $this->controller
->_entryURL
) {
603 $this->addElement('hidden', 'entryURL', $this->controller
->_entryURL
);
606 $this->buildQuickForm();
608 $defaults = $this->setDefaultValues();
609 unset($defaults['qfKey']);
611 if (!empty($defaults)) {
612 $this->setDefaults($defaults);
615 // call the form hook
616 // also call the hook function so any modules can set their own custom defaults
617 // the user can do both the form and set default values with this hook
618 CRM_Utils_Hook
::buildForm(get_class($this), $this);
622 //Set html data-attribute to enable warning user of unsaved changes
623 if ($this->unsavedChangesWarn
=== TRUE
624 ||
(!isset($this->unsavedChangesWarn
)
625 && ($this->_action
& CRM_Core_Action
::ADD ||
$this->_action
& CRM_Core_Action
::UPDATE
)
628 $this->setAttribute('data-warn-changes', 'true');
633 * Add default Next / Back buttons.
635 * @param array $params
636 * Array of associative arrays in the order in which the buttons should be
637 * displayed. The associate array has 3 fields: 'type', 'name' and 'isDefault'
638 * The base form class will define a bunch of static arrays for commonly used
641 public function addButtons($params) {
642 $prevnext = $spacing = [];
643 foreach ($params as $button) {
644 if (!empty($button['submitOnce'])) {
645 $button['js']['onclick'] = "return submitOnce(this,'{$this->_name}','" . ts('Processing') . "');";
648 $attrs = ['class' => 'crm-form-submit'] +
(array) CRM_Utils_Array
::value('js', $button);
650 if (!empty($button['class'])) {
651 $attrs['class'] .= ' ' . $button['class'];
654 if (!empty($button['isDefault'])) {
655 $attrs['class'] .= ' default';
658 if (in_array($button['type'], ['upload', 'next', 'submit', 'done', 'process', 'refresh'])) {
659 $attrs['class'] .= ' validate';
660 $defaultIcon = 'fa-check';
663 $attrs['class'] .= ' cancel';
664 $defaultIcon = $button['type'] == 'back' ?
'fa-chevron-left' : 'fa-times';
667 if ($button['type'] === 'reset') {
668 $prevnext[] = $this->createElement($button['type'], 'reset', $button['name'], $attrs);
671 if (!empty($button['subName'])) {
672 if ($button['subName'] == 'new') {
673 $defaultIcon = 'fa-plus-circle';
675 if ($button['subName'] == 'done') {
676 $defaultIcon = 'fa-check-circle';
678 if ($button['subName'] == 'next') {
679 $defaultIcon = 'fa-chevron-right';
683 if (in_array($button['type'], ['next', 'upload', 'done']) && $button['name'] === ts('Save')) {
684 $attrs['accesskey'] = 'S';
686 $icon = CRM_Utils_Array
::value('icon', $button, $defaultIcon);
688 $attrs['crm-icon'] = $icon;
690 $buttonName = $this->getButtonName($button['type'], CRM_Utils_Array
::value('subName', $button));
691 $prevnext[] = $this->createElement('submit', $buttonName, $button['name'], $attrs);
693 if (!empty($button['isDefault'])) {
694 $this->setDefaultAction($button['type']);
697 // if button type is upload, set the enctype
698 if ($button['type'] == 'upload') {
699 $this->updateAttributes(['enctype' => 'multipart/form-data']);
700 $this->setMaxFileSize();
703 // hack - addGroup uses an array to express variable spacing, read from the last element
704 $spacing[] = CRM_Utils_Array
::value('spacing', $button, self
::ATTR_SPACING
);
706 $this->addGroup($prevnext, 'buttons', '', $spacing, FALSE);
710 * Getter function for Name.
714 public function getName() {
719 * Getter function for State.
723 public function &getState() {
724 return $this->_state
;
728 * Getter function for StateType.
732 public function getStateType() {
733 return $this->_state
->getType();
737 * Getter function for title.
739 * Should be over-ridden by derived class.
743 public function getTitle() {
744 return $this->_title ?
$this->_title
: ts('ERROR: Title is not Set');
748 * Setter function for title.
750 * @param string $title
751 * The title of the form.
753 public function setTitle($title) {
754 $this->_title
= $title;
755 CRM_Utils_System
::setTitle($title);
759 * Assign billing type id to bltID.
761 * @throws CRM_Core_Exception
763 public function assignBillingType() {
764 $this->_bltID
= CRM_Core_BAO_LocationType
::getBilling();
765 $this->set('bltID', $this->_bltID
);
766 $this->assign('bltID', $this->_bltID
);
772 public function getPaymentProcessorID() {
773 return $this->_paymentProcessorID
;
777 * This if a front end form function for setting the payment processor.
779 * It would be good to sync it with the back-end function on abstractEditPayment & use one everywhere.
781 * @param bool $isPayLaterEnabled
783 * @throws \CRM_Core_Exception
785 protected function assignPaymentProcessor($isPayLaterEnabled) {
786 $this->_paymentProcessors
= CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors(
787 [ucfirst($this->_mode
) . 'Mode'],
788 $this->_paymentProcessorIDs
790 if ($isPayLaterEnabled) {
791 $this->_paymentProcessors
[0] = CRM_Financial_BAO_PaymentProcessor
::getPayment(0);
794 if (!empty($this->_paymentProcessors
)) {
795 foreach ($this->_paymentProcessors
as $paymentProcessorID => $paymentProcessorDetail) {
796 if (empty($this->_paymentProcessor
) && $paymentProcessorDetail['is_default'] == 1 ||
(count($this->_paymentProcessors
) == 1)
798 $this->_paymentProcessor
= $paymentProcessorDetail;
799 $this->assign('paymentProcessor', $this->_paymentProcessor
);
800 // Setting this is a bit of a legacy overhang.
801 $this->_paymentObject
= $paymentProcessorDetail['object'];
804 // It's not clear why we set this on the form.
805 $this->set('paymentProcessors', $this->_paymentProcessors
);
808 throw new CRM_Core_Exception(ts('A payment processor configured for this page might be disabled (contact the site administrator for assistance).'));
814 * Format the fields for the payment processor.
816 * In order to pass fields to the payment processor in a consistent way we add some renamed
819 * @param array $fields
823 protected function formatParamsForPaymentProcessor($fields) {
824 // also add location name to the array
825 $this->_params
["address_name-{$this->_bltID}"] = CRM_Utils_Array
::value('billing_first_name', $this->_params
) . ' ' . CRM_Utils_Array
::value('billing_middle_name', $this->_params
) . ' ' . CRM_Utils_Array
::value('billing_last_name', $this->_params
);
826 $this->_params
["address_name-{$this->_bltID}"] = trim($this->_params
["address_name-{$this->_bltID}"]);
827 // Add additional parameters that the payment processors are used to receiving.
828 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
829 $this->_params
['state_province'] = $this->_params
["state_province-{$this->_bltID}"] = $this->_params
["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($this->_params
["billing_state_province_id-{$this->_bltID}"]);
831 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
832 $this->_params
['country'] = $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
835 list($hasAddressField, $addressParams) = CRM_Contribute_BAO_Contribution
::getPaymentProcessorReadyAddressParams($this->_params
, $this->_bltID
);
836 if ($hasAddressField) {
837 $this->_params
= array_merge($this->_params
, $addressParams);
840 $nameFields = ['first_name', 'middle_name', 'last_name'];
841 foreach ($nameFields as $name) {
843 if (array_key_exists("billing_$name", $this->_params
)) {
844 $this->_params
[$name] = $this->_params
["billing_{$name}"];
845 $this->_params
['preserveDBName'] = TRUE;
852 * Handle Payment Processor switching for contribution and event registration forms.
854 * This function is shared between contribution & event forms & this is their common class.
856 * However, this should be seen as an in-progress refactor, the end goal being to also align the
857 * backoffice forms that action payments.
859 * This function overlaps assignPaymentProcessor, in a bad way.
861 protected function preProcessPaymentOptions() {
862 $this->_paymentProcessorID
= NULL;
863 if ($this->_paymentProcessors
) {
864 if (!empty($this->_submitValues
)) {
865 $this->_paymentProcessorID
= CRM_Utils_Array
::value('payment_processor_id', $this->_submitValues
);
866 $this->_paymentProcessor
= CRM_Utils_Array
::value($this->_paymentProcessorID
, $this->_paymentProcessors
);
867 $this->set('type', $this->_paymentProcessorID
);
868 $this->set('mode', $this->_mode
);
869 $this->set('paymentProcessor', $this->_paymentProcessor
);
871 // Set default payment processor
873 foreach ($this->_paymentProcessors
as $values) {
874 if (!empty($values['is_default']) ||
count($this->_paymentProcessors
) == 1) {
875 $this->_paymentProcessorID
= $values['id'];
880 if ($this->_paymentProcessorID
881 ||
(isset($this->_submitValues
['payment_processor_id']) && $this->_submitValues
['payment_processor_id'] == 0)
883 CRM_Core_Payment_ProcessorForm
::preProcess($this);
886 $this->_paymentProcessor
= [];
890 // We save the fact that the profile 'billing' is required on the payment form.
891 // Currently pay-later is the only 'processor' that takes notice of this - but ideally
892 // 1) it would be possible to select the minimum_billing_profile_id for the contribution form
893 // 2) that profile_id would be set on the payment processor
894 // 3) the payment processor would return a billing form that combines these user-configured
895 // minimums with the payment processor minimums. This would lead to fields like 'postal_code'
896 // only being on the form if either the admin has configured it as wanted or the processor
898 $this->assign('billing_profile_id', (CRM_Utils_Array
::value('is_billing_required', $this->_values
) ?
'billing' : ''));
902 * Handle pre approval for processors.
904 * This fits with the flow where a pre-approval is done and then confirmed in the next stage when confirm is hit.
906 * This function is shared between contribution & event forms & this is their common class.
908 * However, this should be seen as an in-progress refactor, the end goal being to also align the
909 * backoffice forms that action payments.
911 * @param array $params
913 protected function handlePreApproval(&$params) {
915 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
916 $params['component'] = 'contribute';
917 $result = $payment->doPreApproval($params);
918 if (empty($result)) {
919 // This could happen, for example, when paypal looks at the button value & decides it is not paypal express.
923 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
924 CRM_Core_Error
::statusBounce(ts('Payment approval failed with message :') . $e->getMessage(), $payment->getCancelUrl($params['qfKey'], CRM_Utils_Array
::value('participant_id', $params)));
927 $this->set('pre_approval_parameters', $result['pre_approval_parameters']);
928 if (!empty($result['redirect_url'])) {
929 CRM_Utils_System
::redirect($result['redirect_url']);
934 * Setter function for options.
936 * @param mixed $options
938 public function setOptions($options) {
939 $this->_options
= $options;
943 * Render form and return contents.
947 public function toSmarty() {
948 $this->preProcessChainSelectFields();
949 $renderer = $this->getRenderer();
950 $this->accept($renderer);
951 $content = $renderer->toArray();
952 $content['formName'] = $this->getName();
954 $content['formClass'] = CRM_Utils_System
::getClassName($this);
959 * Getter function for renderer.
961 * If renderer is not set create one and initialize it.
965 public function &getRenderer() {
966 if (!isset($this->_renderer
)) {
967 $this->_renderer
= CRM_Core_Form_Renderer
::singleton();
969 return $this->_renderer
;
973 * Use the form name to create the tpl file name.
977 public function getTemplateFileName() {
978 $ext = CRM_Extension_System
::singleton()->getMapper();
979 if ($ext->isExtensionClass(CRM_Utils_System
::getClassName($this))) {
980 $filename = $ext->getTemplateName(CRM_Utils_System
::getClassName($this));
981 $tplname = $ext->getTemplatePath(CRM_Utils_System
::getClassName($this)) . DIRECTORY_SEPARATOR
. $filename;
985 CRM_Utils_System
::getClassName($this),
987 '_' => DIRECTORY_SEPARATOR
,
988 '\\' => DIRECTORY_SEPARATOR
,
996 * A wrapper for getTemplateFileName.
998 * This includes calling the hook to prevent us from having to copy & paste the logic of calling the hook.
1000 public function getHookedTemplateFileName() {
1001 $pageTemplateFile = $this->getTemplateFileName();
1002 CRM_Utils_Hook
::alterTemplateFile(get_class($this), $this, 'page', $pageTemplateFile);
1003 return $pageTemplateFile;
1007 * Default extra tpl file basically just replaces .tpl with .extra.tpl.
1009 * i.e. we do not override.
1013 public function overrideExtraTemplateFileName() {
1018 * Error reporting mechanism.
1020 * @param string $message
1024 * @param CRM_Core_DAO $dao
1025 * A data access object on which we perform a rollback if non - empty.
1027 public function error($message, $code = NULL, $dao = NULL) {
1029 $dao->query('ROLLBACK');
1032 $error = CRM_Core_Error
::singleton();
1034 $error->push($code, $message);
1038 * Store the variable with the value in the form scope.
1040 * @param string $name
1041 * Name of the variable.
1042 * @param mixed $value
1043 * Value of the variable.
1045 public function set($name, $value) {
1046 $this->controller
->set($name, $value);
1050 * Get the variable from the form scope.
1052 * @param string $name
1053 * Name of the variable
1057 public function get($name) {
1058 return $this->controller
->get($name);
1062 * Getter for action.
1066 public function getAction() {
1067 return $this->_action
;
1071 * Setter for action.
1073 * @param int $action
1074 * The mode we want to set the form.
1076 public function setAction($action) {
1077 $this->_action
= $action;
1081 * Assign value to name in template.
1083 * @param string $var
1085 * @param mixed $value
1086 * Value of variable.
1088 public function assign($var, $value = NULL) {
1089 self
::$_template->assign($var, $value);
1093 * Assign value to name in template by reference.
1095 * @param string $var
1097 * @param mixed $value
1098 * Value of variable.
1100 public function assign_by_ref($var, &$value) {
1101 self
::$_template->assign_by_ref($var, $value);
1105 * Appends values to template variables.
1107 * @param array|string $tpl_var the template variable name(s)
1108 * @param mixed $value
1109 * The value to append.
1110 * @param bool $merge
1112 public function append($tpl_var, $value = NULL, $merge = FALSE) {
1113 self
::$_template->append($tpl_var, $value, $merge);
1117 * Returns an array containing template variables.
1119 * @param string $name
1123 public function get_template_vars($name = NULL) {
1124 return self
::$_template->get_template_vars($name);
1128 * @param string $name
1131 * @param array $attributes
1132 * @param null $separator
1133 * @param bool $required
1135 * @return HTML_QuickForm_group
1137 public function &addRadio($name, $title, $values, $attributes = [], $separator = NULL, $required = FALSE) {
1139 $attributes = $attributes ?
$attributes : [];
1140 $allowClear = !empty($attributes['allowClear']);
1141 unset($attributes['allowClear']);
1142 $attributes['id_suffix'] = $name;
1143 foreach ($values as $key => $var) {
1144 $options[] = $this->createElement('radio', NULL, NULL, $var, $key, $attributes);
1146 $group = $this->addGroup($options, $name, $title, $separator);
1148 $optionEditKey = 'data-option-edit-path';
1149 if (!empty($attributes[$optionEditKey])) {
1150 $group->setAttribute($optionEditKey, $attributes[$optionEditKey]);
1154 $this->addRule($name, ts('%1 is a required field.', [1 => $title]), 'required');
1157 $group->setAttribute('allowClear', TRUE);
1165 * @param bool $allowClear
1166 * @param null $required
1167 * @param array $attributes
1169 public function addYesNo($id, $title, $allowClear = FALSE, $required = NULL, $attributes = []) {
1170 $attributes +
= ['id_suffix' => $id];
1172 $choice[] = $this->createElement('radio', NULL, '11', ts('Yes'), '1', $attributes);
1173 $choice[] = $this->createElement('radio', NULL, '11', ts('No'), '0', $attributes);
1175 $group = $this->addGroup($choice, $id, $title);
1177 $group->setAttribute('allowClear', TRUE);
1180 $this->addRule($id, ts('%1 is a required field.', [1 => $title]), 'required');
1188 * @param null $other
1189 * @param null $attributes
1190 * @param null $required
1191 * @param null $javascriptMethod
1192 * @param string $separator
1193 * @param bool $flipValues
1195 public function addCheckBox(
1196 $id, $title, $values, $other = NULL,
1197 $attributes = NULL, $required = NULL,
1198 $javascriptMethod = NULL,
1199 $separator = '<br />', $flipValues = FALSE
1203 if ($javascriptMethod) {
1204 foreach ($values as $key => $var) {
1206 $options[] = $this->createElement('checkbox', $var, NULL, $key, $javascriptMethod, $attributes);
1209 $options[] = $this->createElement('checkbox', $key, NULL, $var, $javascriptMethod, $attributes);
1214 foreach ($values as $key => $var) {
1216 $options[] = $this->createElement('checkbox', $var, NULL, $key, $attributes);
1219 $options[] = $this->createElement('checkbox', $key, NULL, $var, $attributes);
1224 $group = $this->addGroup($options, $id, $title, $separator);
1225 $optionEditKey = 'data-option-edit-path';
1226 if (!empty($attributes[$optionEditKey])) {
1227 $group->setAttribute($optionEditKey, $attributes[$optionEditKey]);
1231 $this->addElement('text', $id . '_other', ts('Other'), $attributes[$id . '_other']);
1236 ts('%1 is a required field.', [1 => $title]),
1242 public function resetValues() {
1243 $data = $this->controller
->container();
1244 $data['values'][$this->_name
] = [];
1248 * Simple shell that derived classes can call to add buttons to
1249 * the form with a customized title for the main Submit
1251 * @param string $title
1252 * Title of the main button.
1253 * @param string $nextType
1254 * Button type for the form after processing.
1255 * @param string $backType
1256 * @param bool|string $submitOnce If true, add javascript to next button submit which prevents it from being clicked more than once
1258 public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
1260 if ($backType != NULL) {
1262 'type' => $backType,
1263 'name' => ts('Previous'),
1266 if ($nextType != NULL) {
1268 'type' => $nextType,
1270 'isDefault' => TRUE,
1273 $nextButton['js'] = ['onclick' => "return submitOnce(this,'{$this->_name}','" . ts('Processing') . "');"];
1275 $buttons[] = $nextButton;
1277 $this->addButtons($buttons);
1281 * @param string $name
1282 * @param string $from
1284 * @param string $label
1285 * @param string $dateFormat
1286 * @param bool $required
1287 * @param bool $displayTime
1289 public function addDateRange($name, $from = '_from', $to = '_to', $label = 'From:', $dateFormat = 'searchDate', $required = FALSE, $displayTime = FALSE) {
1291 $this->addDateTime($name . $from, $label, $required, ['formatType' => $dateFormat]);
1292 $this->addDateTime($name . $to, ts('To:'), $required, ['formatType' => $dateFormat]);
1295 $this->addDate($name . $from, $label, $required, ['formatType' => $dateFormat]);
1296 $this->addDate($name . $to, ts('To:'), $required, ['formatType' => $dateFormat]);
1301 * Add a search for a range using date picker fields.
1303 * @param string $fieldName
1304 * @param string $label
1305 * @param bool $isDateTime
1306 * Is this a date-time field (not just date).
1307 * @param bool $required
1308 * @param string $fromLabel
1309 * @param string $toLabel
1311 public function addDatePickerRange($fieldName, $label, $isDateTime = FALSE, $required = FALSE, $fromLabel = 'From', $toLabel = 'To') {
1314 '' => ts('- any -'),
1315 0 => ts('Choose Date Range'),
1316 ] + CRM_Core_OptionGroup
::values('relative_date_filters');
1318 $this->add('select',
1319 "{$fieldName}_relative",
1323 ['class' => 'crm-select2']
1325 $attributes = ['format' => 'searchDate'];
1326 $extra = ['time' => $isDateTime];
1327 $this->add('datepicker', $fieldName . '_low', ts($fromLabel), $attributes, $required, $extra);
1328 $this->add('datepicker', $fieldName . '_high', ts($toLabel), $attributes, $required, $extra);
1332 * Based on form action, return a string representing the api action.
1333 * Used by addField method.
1337 protected function getApiAction() {
1338 $action = $this->getAction();
1339 if ($action & (CRM_Core_Action
::UPDATE + CRM_Core_Action
::ADD
)) {
1342 if ($action & (CRM_Core_Action
::VIEW + CRM_Core_Action
::BROWSE + CRM_Core_Action
::BASIC + CRM_Core_Action
::ADVANCED + CRM_Core_Action
::PREVIEW
)) {
1345 if ($action & (CRM_Core_Action
::DELETE
)) {
1348 // If you get this exception try adding more cases above.
1349 throw new Exception("Cannot determine api action for " . get_class($this) . '.' . 'CRM_Core_Action "' . CRM_Core_Action
::description($action) . '" not recognized.');
1353 * Classes extending CRM_Core_Form should implement this method.
1356 public function getDefaultEntity() {
1357 throw new Exception("Cannot determine default entity. " . get_class($this) . " should implement getDefaultEntity().");
1361 * Classes extending CRM_Core_Form should implement this method.
1363 * TODO: Merge with CRM_Core_DAO::buildOptionsContext($context) and add validation.
1366 public function getDefaultContext() {
1367 throw new Exception("Cannot determine default context. " . get_class($this) . " should implement getDefaultContext().");
1371 * Adds a select based on field metadata.
1372 * TODO: This could be even more generic and widget type (select in this case) could also be read from metadata
1373 * Perhaps a method like $form->bind($name) which would look up all metadata for named field
1375 * Field name to go on the form.
1376 * @param array $props
1377 * Mix of html attributes and special properties, namely.
1378 * - entity (api entity name, can usually be inferred automatically from the form class)
1379 * - field (field name - only needed if different from name used on the form)
1380 * - option_url - path to edit this option list - usually retrieved automatically - set to NULL to disable link
1381 * - placeholder - set to NULL to disable
1383 * - context - @see CRM_Core_DAO::buildOptionsContext
1384 * @param bool $required
1385 * @throws CRM_Core_Exception
1386 * @return HTML_QuickForm_Element
1388 public function addSelect($name, $props = [], $required = FALSE) {
1389 if (!isset($props['entity'])) {
1390 $props['entity'] = $this->getDefaultEntity();
1392 if (!isset($props['field'])) {
1393 $props['field'] = strrpos($name, '[') ?
rtrim(substr($name, 1 +
strrpos($name, '[')), ']') : $name;
1395 if (!isset($props['context'])) {
1397 $props['context'] = $this->getDefaultContext();
1399 // This is not a required param, so we'll ignore if this doesn't exist.
1400 catch (Exception
$e) {
1403 // Fetch options from the api unless passed explicitly
1404 if (isset($props['options'])) {
1405 $options = $props['options'];
1408 $info = civicrm_api3($props['entity'], 'getoptions', $props);
1409 $options = $info['values'];
1411 if (!array_key_exists('placeholder', $props)) {
1412 $props['placeholder'] = $required ?
ts('- select -') : CRM_Utils_Array
::value('context', $props) == 'search' ?
ts('- any -') : ts('- none -');
1414 // Handle custom field
1415 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
1416 list(, $id) = explode('_', $name);
1417 $label = isset($props['label']) ?
$props['label'] : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', 'label', $id);
1418 $gid = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', 'option_group_id', $id);
1419 if (CRM_Utils_Array
::value('context', $props) != 'search') {
1420 $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);
1425 $info = civicrm_api3($props['entity'], 'getfields');
1426 foreach ($info['values'] as $uniqueName => $fieldSpec) {
1428 $uniqueName === $props['field'] ||
1429 CRM_Utils_Array
::value('name', $fieldSpec) === $props['field'] ||
1430 in_array($props['field'], CRM_Utils_Array
::value('api.aliases', $fieldSpec, []))
1435 $label = isset($props['label']) ?
$props['label'] : $fieldSpec['title'];
1436 if (CRM_Utils_Array
::value('context', $props) != 'search') {
1437 $props['data-option-edit-path'] = array_key_exists('option_url', $props) ?
$props['option_url'] : CRM_Core_PseudoConstant
::getOptionEditUrl($fieldSpec);
1440 $props['class'] = (isset($props['class']) ?
$props['class'] . ' ' : '') . "crm-select2";
1441 $props['data-api-entity'] = $props['entity'];
1442 $props['data-api-field'] = $props['field'];
1443 CRM_Utils_Array
::remove($props, 'label', 'entity', 'field', 'option_url', 'options', 'context');
1444 return $this->add('select', $name, $label, $options, $required, $props);
1448 * Adds a field based on metadata.
1451 * Field name to go on the form.
1452 * @param array $props
1453 * Mix of html attributes and special properties, namely.
1454 * - entity (api entity name, can usually be inferred automatically from the form class)
1455 * - name (field name - only needed if different from name used on the form)
1456 * - option_url - path to edit this option list - usually retrieved automatically - set to NULL to disable link
1457 * - placeholder - set to NULL to disable
1459 * - context - @see CRM_Core_DAO::buildOptionsContext
1460 * @param bool $required
1461 * @param bool $legacyDate
1462 * Temporary param to facilitate the conversion of fields to use the datepicker in
1463 * a controlled way. To convert the field the jcalendar code needs to be removed from the
1464 * tpl as well. That file is intended to be EOL.
1466 * @throws \CiviCRM_API3_Exception
1467 * @throws \Exception
1469 * HTML_QuickForm_Element
1472 public function addField($name, $props = [], $required = FALSE, $legacyDate = TRUE) {
1474 if (empty($props['context'])) {
1475 $props['context'] = $this->getDefaultContext();
1477 $context = $props['context'];
1479 if (empty($props['entity'])) {
1480 $props['entity'] = $this->getDefaultEntity();
1483 if (empty($props['name'])) {
1484 $props['name'] = strrpos($name, '[') ?
rtrim(substr($name, 1 +
strrpos($name, '[')), ']') : $name;
1487 if (empty($props['action'])) {
1488 $props['action'] = $this->getApiAction();
1491 // Handle custom fields
1492 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
1493 $fieldId = (int) substr($name, 7);
1494 return CRM_Core_BAO_CustomField
::addQuickFormElement($this, $name, $fieldId, $required, $context == 'search', CRM_Utils_Array
::value('label', $props));
1497 // Core field - get metadata.
1498 $fieldSpec = civicrm_api3($props['entity'], 'getfield', $props);
1499 $fieldSpec = $fieldSpec['values'];
1500 $fieldSpecLabel = isset($fieldSpec['html']['label']) ?
$fieldSpec['html']['label'] : CRM_Utils_Array
::value('title', $fieldSpec);
1501 $label = CRM_Utils_Array
::value('label', $props, $fieldSpecLabel);
1503 $widget = isset($props['type']) ?
$props['type'] : $fieldSpec['html']['type'];
1504 if ($widget == 'TextArea' && $context == 'search') {
1508 $isSelect = (in_array($widget, [
1517 // Fetch options from the api unless passed explicitly.
1518 if (isset($props['options'])) {
1519 $options = $props['options'];
1522 $options = isset($fieldSpec['options']) ?
$fieldSpec['options'] : NULL;
1524 if ($context == 'search') {
1525 $widget = $widget == 'Select2' ?
$widget : 'Select';
1526 $props['multiple'] = CRM_Utils_Array
::value('multiple', $props, TRUE);
1529 // Add data for popup link.
1530 $canEditOptions = CRM_Core_Permission
::check('administer CiviCRM');
1531 $hasOptionUrl = !empty($props['option_url']);
1532 $optionUrlKeyIsSet = array_key_exists('option_url', $props);
1533 $shouldAdd = $context !== 'search' && $isSelect && $canEditOptions;
1535 // Only add if key is not set, or if non-empty option url is provided
1536 if (($hasOptionUrl ||
!$optionUrlKeyIsSet) && $shouldAdd) {
1537 $optionUrl = $hasOptionUrl ?
$props['option_url'] :
1538 CRM_Core_PseudoConstant
::getOptionEditUrl($fieldSpec);
1539 $props['data-option-edit-path'] = $optionUrl;
1540 $props['data-api-entity'] = $props['entity'];
1541 $props['data-api-field'] = $props['name'];
1544 $props +
= CRM_Utils_Array
::value('html', $fieldSpec, []);
1545 CRM_Utils_Array
::remove($props, 'entity', 'name', 'context', 'label', 'action', 'type', 'option_url', 'options');
1547 // TODO: refactor switch statement, to separate methods.
1553 //TODO: Autodetect ranges
1554 $props['size'] = isset($props['size']) ?
$props['size'] : 60;
1555 return $this->add(strtolower($widget), $name, $label, $props, $required);
1558 return $this->add('hidden', $name, NULL, $props, $required);
1561 //Set default columns and rows for textarea.
1562 $props['rows'] = isset($props['rows']) ?
$props['rows'] : 4;
1563 $props['cols'] = isset($props['cols']) ?
$props['cols'] : 60;
1564 if (empty($props['maxlength']) && isset($fieldSpec['length'])) {
1565 $props['maxlength'] = $fieldSpec['length'];
1567 return $this->add('textarea', $name, $label, $props, $required);
1570 // This is a white list for fields that have been tested with
1571 // date picker. We should be able to remove the other
1573 //TODO: add range support
1574 //TODO: Add date formats
1575 //TODO: Add javascript template for dates.
1576 return $this->addDate($name, $label, $required, $props);
1579 $fieldSpec = CRM_Utils_Date
::addDateMetadataToField($fieldSpec, $fieldSpec);
1580 $attributes = ['format' => $fieldSpec['date_format']];
1581 return $this->add('datepicker', $name, $label, $attributes, $required, $fieldSpec['datepicker']['extra']);
1585 $separator = isset($props['separator']) ?
$props['separator'] : NULL;
1586 unset($props['separator']);
1587 if (!isset($props['allowClear'])) {
1588 $props['allowClear'] = !$required;
1590 return $this->addRadio($name, $label, $options, $props, $separator, $required);
1594 'required' => $required,
1596 'multiple' => $context == 'search',
1598 return $this->addChainSelect($name, $props);
1602 $props['class'] = CRM_Utils_Array
::value('class', $props, 'big') . ' crm-select2';
1603 if (!array_key_exists('placeholder', $props)) {
1604 $props['placeholder'] = $required ?
ts('- select -') : ($context == 'search' ?
ts('- any -') : ts('- none -'));
1606 // TODO: Add and/or option for fields that store multiple values
1607 return $this->add(strtolower($widget), $name, $label, $options, $required, $props);
1609 case 'CheckBoxGroup':
1610 return $this->addCheckBox($name, $label, array_flip($options), $required, $props);
1613 return $this->addRadio($name, $label, $options, $props, NULL, $required);
1616 $text = isset($props['text']) ?
$props['text'] : NULL;
1617 unset($props['text']);
1618 return $this->addElement('checkbox', $name, $label, $text, $props);
1620 //add support for 'Advcheckbox' field
1622 $text = isset($props['text']) ?
$props['text'] : NULL;
1623 unset($props['text']);
1624 return $this->addElement('advcheckbox', $name, $label, $text, $props);
1627 // We should not build upload file in search mode.
1628 if ($context == 'search') {
1631 $file = $this->add('file', $name, $label, $props, $required);
1632 $this->addUploadElement($name);
1635 case 'RichTextEditor':
1636 return $this->add('wysiwyg', $name, $label, $props, $required);
1639 return $this->addEntityRef($name, $label, $props, $required);
1642 $props['size'] = isset($props['size']) ?
$props['size'] : 60;
1643 return $this->add('password', $name, $label, $props, $required);
1645 // Check datatypes of fields
1649 //case read only fields
1651 throw new Exception("Unsupported html-element " . $widget);
1656 * Add a widget for selecting/editing/creating/copying a profile form
1658 * @param string $name
1659 * HTML form-element name.
1660 * @param string $label
1662 * @param string $allowCoreTypes
1663 * Only present a UFGroup if its group_type includes a subset of $allowCoreTypes; e.g. 'Individual', 'Activity'.
1664 * @param string $allowSubTypes
1665 * Only present a UFGroup if its group_type is compatible with $allowSubypes.
1666 * @param array $entities
1667 * @param bool $default
1669 * @param string $usedFor
1671 public function addProfileSelector($name, $label, $allowCoreTypes, $allowSubTypes, $entities, $default = FALSE, $usedFor = NULL) {
1673 // FIXME: Instead of adhoc serialization, use a single json_encode()
1674 CRM_UF_Page_ProfileEditor
::registerProfileScripts();
1675 CRM_UF_Page_ProfileEditor
::registerSchemas(CRM_Utils_Array
::collect('entity_type', $entities));
1676 $this->add('text', $name, $label, [
1677 'class' => 'crm-profile-selector',
1678 // Note: client treats ';;' as equivalent to \0, and ';;' works better in HTML
1679 'data-group-type' => CRM_Core_BAO_UFGroup
::encodeGroupType($allowCoreTypes, $allowSubTypes, ';;'),
1680 'data-entities' => json_encode($entities),
1682 'data-default' => $default,
1683 'data-usedfor' => json_encode($usedFor),
1690 public function getRootTitle() {
1697 public function getCompleteTitle() {
1698 return $this->getRootTitle() . $this->getTitle();
1702 * @return CRM_Core_Smarty
1704 public static function &getTemplate() {
1705 return self
::$_template;
1709 * @param $elementName
1711 public function addUploadElement($elementName) {
1712 $uploadNames = $this->get('uploadNames');
1713 if (!$uploadNames) {
1716 if (is_array($elementName)) {
1717 foreach ($elementName as $name) {
1718 if (!in_array($name, $uploadNames)) {
1719 $uploadNames[] = $name;
1724 if (!in_array($elementName, $uploadNames)) {
1725 $uploadNames[] = $elementName;
1728 $this->set('uploadNames', $uploadNames);
1730 $config = CRM_Core_Config
::singleton();
1731 if (!empty($uploadNames)) {
1732 $this->controller
->addUploadAction($config->customFileUploadDir
, $uploadNames);
1741 public function getVar($name) {
1742 return isset($this->$name) ?
$this->$name : NULL;
1749 public function setVar($name, $value) {
1750 $this->$name = $value;
1757 * Use $this->add('datepicker', ...) instead.
1759 * @param string $name
1760 * Name of the element.
1761 * @param string $label
1762 * Label of the element.
1763 * @param bool $required
1765 * @param array $attributes
1768 public function addDate($name, $label, $required = FALSE, $attributes = NULL) {
1769 if (!empty($attributes['formatType'])) {
1770 // get actual format
1771 $params = ['name' => $attributes['formatType']];
1774 // cache date information
1776 $key = "dateFormat_" . str_replace(' ', '_', $attributes['formatType']);
1777 if (empty($dateFormat[$key])) {
1778 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
1779 $dateFormat[$key] = $values;
1782 $values = $dateFormat[$key];
1785 if ($values['date_format']) {
1786 $attributes['format'] = $values['date_format'];
1789 if (!empty($values['time_format'])) {
1790 $attributes['timeFormat'] = $values['time_format'];
1792 $attributes['startOffset'] = $values['start'];
1793 $attributes['endOffset'] = $values['end'];
1796 $config = CRM_Core_Config
::singleton();
1797 if (empty($attributes['format'])) {
1798 $attributes['format'] = $config->dateInputFormat
;
1801 if (!isset($attributes['startOffset'])) {
1802 $attributes['startOffset'] = 10;
1805 if (!isset($attributes['endOffset'])) {
1806 $attributes['endOffset'] = 10;
1809 $this->add('text', $name, $label, $attributes);
1811 if (!empty($attributes['addTime']) ||
!empty($attributes['timeFormat'])) {
1813 if (!isset($attributes['timeFormat'])) {
1814 $timeFormat = $config->timeInputFormat
;
1817 $timeFormat = $attributes['timeFormat'];
1820 // 1 - 12 hours and 2 - 24 hours, but for jquery widget it is 0 and 1 respectively
1822 $show24Hours = TRUE;
1823 if ($timeFormat == 1) {
1824 $show24Hours = FALSE;
1827 //CRM-6664 -we are having time element name
1828 //in either flat string or an array format.
1829 $elementName = $name . '_time';
1830 if (substr($name, -1) == ']') {
1831 $elementName = substr($name, 0, strlen($name) - 1) . '_time]';
1834 $this->add('text', $elementName, ts('Time'), ['timeFormat' => $show24Hours]);
1839 $this->addRule($name, ts('Please select %1', [1 => $label]), 'required');
1840 if (!empty($attributes['addTime']) && !empty($attributes['addTimeRequired'])) {
1841 $this->addRule($elementName, ts('Please enter a time.'), 'required');
1847 * Function that will add date and time.
1850 * Use $this->add('datepicker', ...) instead.
1852 * @param string $name
1853 * @param string $label
1854 * @param bool $required
1855 * @param null $attributes
1857 public function addDateTime($name, $label, $required = FALSE, $attributes = NULL) {
1858 $addTime = ['addTime' => TRUE];
1859 if (is_array($attributes)) {
1860 $attributes = array_merge($attributes, $addTime);
1863 $attributes = $addTime;
1866 $this->addDate($name, $label, $required, $attributes);
1870 * Add a currency and money element to the form.
1872 * @param string $name
1873 * @param string $label
1874 * @param bool $required
1875 * @param null $attributes
1876 * @param bool $addCurrency
1877 * @param string $currencyName
1878 * @param null $defaultCurrency
1879 * @param bool $freezeCurrency
1881 * @return \HTML_QuickForm_Element
1883 public function addMoney(
1888 $addCurrency = TRUE,
1889 $currencyName = 'currency',
1890 $defaultCurrency = NULL,
1891 $freezeCurrency = FALSE
1893 $element = $this->add('text', $name, $label, $attributes, $required);
1894 $this->addRule($name, ts('Please enter a valid amount.'), 'money');
1897 $ele = $this->addCurrency($currencyName, NULL, TRUE, $defaultCurrency, $freezeCurrency);
1904 * Add currency element to the form.
1906 * @param string $name
1907 * @param null $label
1908 * @param bool $required
1909 * @param string $defaultCurrency
1910 * @param bool $freezeCurrency
1911 * @param bool $setDefaultCurrency
1913 public function addCurrency(
1917 $defaultCurrency = NULL,
1918 $freezeCurrency = FALSE,
1919 $setDefaultCurrency = TRUE
1921 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
1922 if (!empty($defaultCurrency) && !array_key_exists($defaultCurrency, $currencies)) {
1923 Civi
::log()->warning('addCurrency: Currency ' . $defaultCurrency . ' is disabled but still in use!');
1924 $currencies[$defaultCurrency] = $defaultCurrency;
1926 $options = ['class' => 'crm-select2 eight'];
1928 $currencies = ['' => ''] +
$currencies;
1929 $options['placeholder'] = ts('- none -');
1931 $ele = $this->add('select', $name, $label, $currencies, $required, $options);
1932 if ($freezeCurrency) {
1935 if (!$defaultCurrency) {
1936 $config = CRM_Core_Config
::singleton();
1937 $defaultCurrency = $config->defaultCurrency
;
1939 // In some case, setting currency field by default might override the default value
1940 // as encountered in CRM-20527 for batch data entry
1941 if ($setDefaultCurrency) {
1942 $this->setDefaults([$name => $defaultCurrency]);
1947 * Create a single or multiple entity ref field.
1948 * @param string $name
1949 * @param string $label
1950 * @param array $props
1951 * Mix of html and widget properties, including:.
1952 * - select - params to give to select2 widget
1953 * - entity - defaults to Contact
1954 * - create - can the user create a new entity on-the-fly?
1955 * Set to TRUE if entity is contact and you want the default profiles,
1956 * or pass in your own set of links. @see CRM_Campaign_BAO_Campaign::getEntityRefCreateLinks for format
1957 * note that permissions are checked automatically
1958 * - api - array of settings for the getlist api wrapper
1959 * note that it accepts a 'params' setting which will be passed to the underlying api
1960 * - placeholder - string
1962 * - class, etc. - other html properties
1963 * @param bool $required
1965 * @return HTML_QuickForm_Element
1967 public function addEntityRef($name, $label = '', $props = [], $required = FALSE) {
1968 // Default properties
1969 $props['api'] = CRM_Utils_Array
::value('api', $props, []);
1970 $props['entity'] = CRM_Utils_String
::convertStringToCamel(CRM_Utils_Array
::value('entity', $props, 'Contact'));
1971 $props['class'] = ltrim(CRM_Utils_Array
::value('class', $props, '') . ' crm-form-entityref');
1973 if (array_key_exists('create', $props) && empty($props['create'])) {
1974 unset($props['create']);
1977 $props['placeholder'] = CRM_Utils_Array
::value('placeholder', $props, $required ?
ts('- select %1 -', [1 => ts(str_replace('_', ' ', $props['entity']))]) : ts('- none -'));
1980 if (!empty($props['multiple'])) {
1981 $defaults['multiple'] = TRUE;
1983 $props['select'] = CRM_Utils_Array
::value('select', $props, []) +
$defaults;
1985 $this->formatReferenceFieldAttributes($props, get_class($this));
1986 return $this->add('text', $name, $label, $props, $required);
1990 * @param array $props
1991 * @param string $formName
1993 private function formatReferenceFieldAttributes(&$props, $formName) {
1994 CRM_Utils_Hook
::alterEntityRefParams($props, $formName);
1995 $props['data-select-params'] = json_encode($props['select']);
1996 $props['data-api-params'] = $props['api'] ?
json_encode($props['api']) : NULL;
1997 $props['data-api-entity'] = $props['entity'];
1998 if (!empty($props['create'])) {
1999 $props['data-create-links'] = json_encode($props['create']);
2001 CRM_Utils_Array
::remove($props, 'multiple', 'select', 'api', 'entity', 'create');
2005 * Convert all date fields within the params to mysql date ready for the
2006 * BAO layer. In this case fields are checked against the $_datefields defined for the form
2007 * and if time is defined it is incorporated
2009 * @param array $params
2010 * Input params from the form.
2012 * @todo it would probably be better to work on $this->_params than a passed array
2013 * @todo standardise the format which dates are passed to the BAO layer in & remove date
2016 public function convertDateFieldsToMySQL(&$params) {
2017 foreach ($this->_dateFields
as $fieldName => $specs) {
2018 if (!empty($params[$fieldName])) {
2019 $params[$fieldName] = CRM_Utils_Date
::isoToMysql(
2020 CRM_Utils_Date
::processDate(
2021 $params[$fieldName],
2022 CRM_Utils_Array
::value("{$fieldName}_time", $params), TRUE)
2026 if (isset($specs['default'])) {
2027 $params[$fieldName] = date('YmdHis', strtotime($specs['default']));
2034 * @param $elementName
2036 public function removeFileRequiredRules($elementName) {
2037 $this->_required
= array_diff($this->_required
, [$elementName]);
2038 if (isset($this->_rules
[$elementName])) {
2039 foreach ($this->_rules
[$elementName] as $index => $ruleInfo) {
2040 if ($ruleInfo['type'] == 'uploadedfile') {
2041 unset($this->_rules
[$elementName][$index]);
2044 if (empty($this->_rules
[$elementName])) {
2045 unset($this->_rules
[$elementName]);
2051 * Function that can be defined in Form to override or.
2052 * perform specific action on cancel action
2054 public function cancelAction() {
2058 * Helper function to verify that required fields have been filled.
2060 * Typically called within the scope of a FormRule function
2062 * @param array $fields
2063 * @param array $values
2064 * @param array $errors
2066 public static function validateMandatoryFields($fields, $values, &$errors) {
2067 foreach ($fields as $name => $fld) {
2068 if (!empty($fld['is_required']) && CRM_Utils_System
::isNull(CRM_Utils_Array
::value($name, $values))) {
2069 $errors[$name] = ts('%1 is a required field.', [1 => $fld['title']]);
2075 * Get contact if for a form object. Prioritise
2076 * - cid in URL if 0 (on behalf on someoneelse)
2077 * (@todo consider setting a variable if onbehalf for clarity of downstream 'if's
2078 * - logged in user id if it matches the one in the cid in the URL
2079 * - contact id validated from a checksum from a checksum
2080 * - cid from the url if the caller has ACL permission to view
2081 * - fallback is logged in user (or ? NULL if no logged in user) (@todo wouldn't 0 be more intuitive?)
2085 protected function setContactID() {
2086 $tempID = CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
2087 if (isset($this->_params
) && !empty($this->_params
['select_contact_id'])) {
2088 $tempID = $this->_params
['select_contact_id'];
2090 if (isset($this->_params
, $this->_params
[0]) && !empty($this->_params
[0]['select_contact_id'])) {
2091 // event form stores as an indexed array, contribution form not so much...
2092 $tempID = $this->_params
[0]['select_contact_id'];
2095 // force to ignore the authenticated user
2096 if ($tempID === '0' ||
$tempID === 0) {
2097 // we set the cid on the form so that this will be retained for the Confirm page
2098 // in the multi-page form & prevent us returning the $userID when this is called
2100 // we don't really need to set it when $tempID is set because the params have that stored
2101 $this->set('cid', 0);
2102 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $tempID]);
2103 return (int) $tempID;
2106 $userID = $this->getLoggedInUserContactID();
2108 if (!is_null($tempID) && $tempID === $userID) {
2109 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $tempID]);
2110 return (int) $userID;
2113 //check if this is a checksum authentication
2114 $userChecksum = CRM_Utils_Request
::retrieve('cs', 'String', $this);
2115 if ($userChecksum) {
2116 //check for anonymous user.
2117 $validUser = CRM_Contact_BAO_Contact_Utils
::validChecksum($tempID, $userChecksum);
2119 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $tempID]);
2120 CRM_Core_Resources
::singleton()->addVars('coreForm', ['checksum' => $userChecksum]);
2124 // check if user has permission, CRM-12062
2125 elseif ($tempID && CRM_Contact_BAO_Contact_Permission
::allow($tempID)) {
2126 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $tempID]);
2129 if (is_numeric($userID)) {
2130 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $userID]);
2132 return is_numeric($userID) ?
$userID : NULL;
2136 * Get the contact id that the form is being submitted for.
2140 public function getContactID() {
2141 return $this->setContactID();
2145 * Get the contact id of the logged in user.
2147 public function getLoggedInUserContactID() {
2148 // check if the user is logged in and has a contact ID
2149 $session = CRM_Core_Session
::singleton();
2150 return $session->get('userID');
2154 * Add autoselector field -if user has permission to view contacts
2155 * If adding this to a form you also need to add to the tpl e.g
2157 * {if !empty($selectable)}
2158 * <div class="crm-summary-row">
2159 * <div class="crm-label">{$form.select_contact.label}</div>
2160 * <div class="crm-content">
2161 * {$form.select_contact.html}
2166 * @param array $profiles
2167 * Ids of profiles that are on the form (to be autofilled).
2168 * @param array $autoCompleteField
2172 * - url (for ajax lookup)
2174 * @todo add data attributes so we can deal with multiple instances on a form
2176 public function addAutoSelector($profiles = [], $autoCompleteField = []) {
2177 $autoCompleteField = array_merge([
2178 'id_field' => 'select_contact_id',
2179 'placeholder' => ts('Select someone else ...'),
2180 'show_hide' => TRUE,
2181 'api' => ['params' => ['contact_type' => 'Individual']],
2182 ], $autoCompleteField);
2184 if ($this->canUseAjaxContactLookups()) {
2185 $this->assign('selectable', $autoCompleteField['id_field']);
2186 $this->addEntityRef($autoCompleteField['id_field'], NULL, [
2187 'placeholder' => $autoCompleteField['placeholder'],
2188 'api' => $autoCompleteField['api'],
2191 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/AlternateContactSelector.js', 1, 'html-header')
2193 'form' => ['autocompletes' => $autoCompleteField],
2194 'ids' => ['profile' => $profiles],
2201 public function canUseAjaxContactLookups() {
2202 if (0 < (civicrm_api3('contact', 'getcount', ['check_permissions' => 1])) &&
2203 CRM_Core_Permission
::check([['access AJAX API', 'access CiviCRM']])
2210 * Add the options appropriate to cid = zero - ie. autocomplete
2212 * @todo there is considerable code duplication between the contribution forms & event forms. It is apparent
2213 * that small pieces of duplication are not being refactored into separate functions because their only shared parent
2214 * is this form. Inserting a class FrontEndForm.php between the contribution & event & this class would allow functions like this
2215 * and a dozen other small ones to be refactored into a shared parent with the reduction of much code duplication
2217 * @param $onlinePaymentProcessorEnabled
2219 public function addCIDZeroOptions($onlinePaymentProcessorEnabled) {
2220 $this->assign('nocid', TRUE);
2222 if ($this->_values
['custom_pre_id']) {
2223 $profiles[] = $this->_values
['custom_pre_id'];
2225 if ($this->_values
['custom_post_id']) {
2226 $profiles = array_merge($profiles, (array) $this->_values
['custom_post_id']);
2228 if ($onlinePaymentProcessorEnabled) {
2229 $profiles[] = 'billing';
2231 if (!empty($this->_values
)) {
2232 $this->addAutoSelector($profiles);
2237 * Set default values on form for given contact (or no contact defaults)
2239 * @param mixed $profile_id
2240 * (can be id, or profile name).
2241 * @param int $contactID
2245 public function getProfileDefaults($profile_id = 'Billing', $contactID = NULL) {
2247 $defaults = civicrm_api3('profile', 'getsingle', [
2248 'profile_id' => (array) $profile_id,
2249 'contact_id' => $contactID,
2253 catch (Exception
$e) {
2254 // the try catch block gives us silent failure -not 100% sure this is a good idea
2255 // as silent failures are often worse than noisy ones
2261 * Sets form attribute.
2264 public function preventAjaxSubmit() {
2265 $this->setAttribute('data-no-ajax-submit', 'true');
2269 * Sets form attribute.
2272 public function allowAjaxSubmit() {
2273 $this->removeAttribute('data-no-ajax-submit');
2277 * Sets page title based on entity and action.
2278 * @param string $entityLabel
2280 public function setPageTitle($entityLabel) {
2281 switch ($this->_action
) {
2282 case CRM_Core_Action
::ADD
:
2283 CRM_Utils_System
::setTitle(ts('New %1', [1 => $entityLabel]));
2286 case CRM_Core_Action
::UPDATE
:
2287 CRM_Utils_System
::setTitle(ts('Edit %1', [1 => $entityLabel]));
2290 case CRM_Core_Action
::VIEW
:
2291 case CRM_Core_Action
::PREVIEW
:
2292 CRM_Utils_System
::setTitle(ts('View %1', [1 => $entityLabel]));
2295 case CRM_Core_Action
::DELETE
:
2296 CRM_Utils_System
::setTitle(ts('Delete %1', [1 => $entityLabel]));
2302 * Create a chain-select target field. All settings are optional; the defaults usually work.
2304 * @param string $elementName
2305 * @param array $settings
2307 * @return HTML_QuickForm_Element
2309 public function addChainSelect($elementName, $settings = []) {
2310 $props = $settings +
= [
2311 'control_field' => str_replace(['state_province', 'StateProvince', 'county', 'County'], [
2317 'data-callback' => strpos($elementName, 'rovince') ?
'civicrm/ajax/jqState' : 'civicrm/ajax/jqCounty',
2318 'label' => strpos($elementName, 'rovince') ?
ts('State/Province') : ts('County'),
2319 'data-empty-prompt' => strpos($elementName, 'rovince') ?
ts('Choose country first') : ts('Choose state first'),
2320 'data-none-prompt' => ts('- N/A -'),
2321 'multiple' => FALSE,
2322 'required' => FALSE,
2323 'placeholder' => empty($settings['required']) ?
ts('- none -') : ts('- select -'),
2325 CRM_Utils_Array
::remove($props, 'label', 'required', 'control_field', 'context');
2326 $props['class'] = (empty($props['class']) ?
'' : "{$props['class']} ") . 'crm-select2';
2327 $props['data-select-prompt'] = $props['placeholder'];
2328 $props['data-name'] = $elementName;
2330 $this->_chainSelectFields
[$settings['control_field']] = $elementName;
2332 // Passing NULL instead of an array of options
2333 // CRM-15225 - normally QF will reject any selected values that are not part of the field's options, but due to a
2334 // quirk in our patched version of HTML_QuickForm_select, this doesn't happen if the options are NULL
2335 // which seems a bit dirty but it allows our dynamically-popuplated select element to function as expected.
2336 return $this->add('select', $elementName, $settings['label'], NULL, $settings['required'], $props);
2340 * Add actions menu to results form.
2342 * @param array $tasks
2344 public function addTaskMenu($tasks) {
2345 if (is_array($tasks) && !empty($tasks)) {
2346 // Set constants means this will always load with an empty value, not reloading any submitted value.
2347 // This is appropriate as it is a pseudofield.
2348 $this->setConstants(['task' => '']);
2349 $this->assign('taskMetaData', $tasks);
2350 $select = $this->add('select', 'task', NULL, ['' => ts('Actions')], FALSE, [
2351 'class' => 'crm-select2 crm-action-menu fa-check-circle-o huge crm-search-result-actions',
2354 foreach ($tasks as $key => $task) {
2356 if (isset($task['data'])) {
2357 foreach ($task['data'] as $dataKey => $dataValue) {
2358 $attributes['data-' . $dataKey] = $dataValue;
2361 $select->addOption($task['title'], $key, $attributes);
2363 if (empty($this->_actionButtonName
)) {
2364 $this->_actionButtonName
= $this->getButtonName('next', 'action');
2366 $this->assign('actionButtonName', $this->_actionButtonName
);
2367 $this->add('submit', $this->_actionButtonName
, ts('Go'), ['class' => 'hiddenElement crm-search-go-button']);
2369 // Radio to choose "All items" or "Selected items only"
2370 $selectedRowsRadio = $this->addElement('radio', 'radio_ts', NULL, '', 'ts_sel', ['checked' => 'checked']);
2371 $allRowsRadio = $this->addElement('radio', 'radio_ts', NULL, '', 'ts_all');
2372 $this->assign('ts_sel_id', $selectedRowsRadio->_attributes
['id']);
2373 $this->assign('ts_all_id', $allRowsRadio->_attributes
['id']);
2375 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header');
2380 * Set options and attributes for chain select fields based on the controlling field's value
2382 private function preProcessChainSelectFields() {
2383 foreach ($this->_chainSelectFields
as $control => $target) {
2384 // The 'target' might get missing if extensions do removeElement() in a form hook.
2385 if ($this->elementExists($target)) {
2386 $targetField = $this->getElement($target);
2387 $targetType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ?
'county' : 'stateProvince';
2389 // If the control field is on the form, setup chain-select and dynamically populate options
2390 if ($this->elementExists($control)) {
2391 $controlField = $this->getElement($control);
2392 $controlType = $targetType == 'county' ?
'stateProvince' : 'country';
2394 $targetField->setAttribute('class', $targetField->getAttribute('class') . ' crm-chain-select-target');
2396 $css = (string) $controlField->getAttribute('class');
2397 $controlField->updateAttributes([
2398 'class' => ($css ?
"$css " : 'crm-select2 ') . 'crm-chain-select-control',
2399 'data-target' => $target,
2401 $controlValue = $controlField->getValue();
2402 if ($controlValue) {
2403 $options = CRM_Core_BAO_Location
::getChainSelectValues($controlValue, $controlType, TRUE);
2405 $targetField->setAttribute('placeholder', $targetField->getAttribute('data-none-prompt'));
2409 $targetField->setAttribute('placeholder', $targetField->getAttribute('data-empty-prompt'));
2410 $targetField->setAttribute('disabled', 'disabled');
2413 // Control field not present - fall back to loading default options
2415 $options = CRM_Core_PseudoConstant
::$targetType();
2417 if (!$targetField->getAttribute('multiple')) {
2418 $options = ['' => $targetField->getAttribute('placeholder')] +
$options;
2419 $targetField->removeAttribute('placeholder');
2421 $targetField->_options
= [];
2422 $targetField->loadArray($options);
2428 * Validate country / state / county match and suppress unwanted "required" errors
2430 private function validateChainSelectFields() {
2431 foreach ($this->_chainSelectFields
as $control => $target) {
2432 if ($this->elementExists($control) && $this->elementExists($target)) {
2433 $controlValue = (array) $this->getElementValue($control);
2434 $targetField = $this->getElement($target);
2435 $controlType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ?
'stateProvince' : 'country';
2436 $targetValue = array_filter((array) $targetField->getValue());
2437 if ($targetValue ||
$this->getElementError($target)) {
2438 $options = CRM_Core_BAO_Location
::getChainSelectValues($controlValue, $controlType, TRUE);
2440 if (!array_intersect($targetValue, array_keys($options))) {
2441 $this->setElementError($target, $controlType == 'country' ?
ts('State/Province does not match the selected Country') : ts('County does not match the selected State/Province'));
2444 // Suppress "required" error for field if it has no options
2445 elseif (!$options) {
2446 $this->setElementError($target, NULL);
2454 * Assign billing name to the template.
2456 * @param array $params
2457 * Form input params, default to $this->_params.
2461 public function assignBillingName($params = []) {
2463 if (empty($params)) {
2464 $params = $this->_params
;
2466 if (!empty($params['billing_first_name'])) {
2467 $name = $params['billing_first_name'];
2470 if (!empty($params['billing_middle_name'])) {
2471 $name .= " {$params['billing_middle_name']}";
2474 if (!empty($params['billing_last_name'])) {
2475 $name .= " {$params['billing_last_name']}";
2477 $name = trim($name);
2478 $this->assign('billingName', $name);
2483 * Get the currency for the form.
2485 * @todo this should be overriden on the forms rather than having this
2486 * historic, possible handling in here. As we clean that up we should
2487 * add deprecation notices into here.
2489 * @param array $submittedValues
2490 * Array allowed so forms inheriting this class do not break.
2491 * Ideally we would make a clear standard around how submitted values
2492 * are stored (is $this->_values consistently doing that?).
2496 public function getCurrency($submittedValues = []) {
2497 $currency = CRM_Utils_Array
::value('currency', $this->_values
);
2498 // For event forms, currency is in a different spot
2499 if (empty($currency)) {
2500 $currency = CRM_Utils_Array
::value('currency', CRM_Utils_Array
::value('event', $this->_values
));
2502 if (empty($currency)) {
2503 $currency = CRM_Utils_Request
::retrieveValue('currency', 'String');
2505 // @todo If empty there is a problem - we should probably put in a deprecation notice
2506 // to warn if that seems to be happening.
2511 * Is the form in view or edit mode.
2513 * The 'addField' function relies on the form action being one of a set list
2514 * of actions. Checking for these allows for an early return.
2518 protected function isFormInViewOrEditMode() {
2519 return in_array($this->_action
, [
2520 CRM_Core_Action
::UPDATE
,
2521 CRM_Core_Action
::ADD
,
2522 CRM_Core_Action
::VIEW
,
2523 CRM_Core_Action
::BROWSE
,
2524 CRM_Core_Action
::BASIC
,
2525 CRM_Core_Action
::ADVANCED
,
2526 CRM_Core_Action
::PREVIEW
,