3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 = array();
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 = array();
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
166 protected $unsavedChangesWarn;
169 * What to return to the client if in ajax mode (snippet=json)
173 public $ajaxResponse = array();
176 * Url path used to reach this page
180 public $urlPath = array();
183 * @var CRM_Core_Controller
188 * Constants for attributes for various form elements
189 * attempt to standardize on the number of variations that we
190 * use of the below form elements
194 const ATTR_SPACING
= ' ';
197 * All checkboxes are defined with a common prefix. This allows us to
198 * have the same javascript to check / clear all the checkboxes etc
199 * If u have multiple groups of checkboxes, you will need to give them different
200 * ids to avoid potential name collision
204 const CB_PREFIX
= 'mark_x_', CB_PREFIY
= 'mark_y_', CB_PREFIZ
= 'mark_z_', CB_PREFIX_LEN
= 7;
207 * @internal to keep track of chain-select fields
210 private $_chainSelectFields = array();
213 * Extra input types we support via the "add" method
216 public static $html5Types = array(
224 * Constructor for the basic form page.
226 * We should not use QuickForm directly. This class provides a lot
227 * of default convenient functions, rules and buttons
229 * @param object $state
230 * State associated with this form.
231 * @param \const|\enum|int $action The mode the form is operating in (None/Create/View/Update/Delete)
232 * @param string $method
233 * The type of http method used (GET/POST).
234 * @param string $name
235 * The name of the form if different from class name.
237 * @return \CRM_Core_Form
239 public function __construct(
241 $action = CRM_Core_Action
::NONE
,
247 $this->_name
= $name;
250 // CRM-15153 - FIXME this name translates to a DOM id and is not always unique!
251 $this->_name
= CRM_Utils_String
::getClassName(CRM_Utils_System
::getClassName($this));
254 parent
::__construct($this->_name
, $method);
256 $this->_state
=& $state;
258 $this->_state
->setName($this->_name
);
260 $this->_action
= (int) $action;
262 $this->registerRules();
264 // let the constructor initialize this, should happen only once
265 if (!isset(self
::$_template)) {
266 self
::$_template = CRM_Core_Smarty
::singleton();
268 // Workaround for CRM-15153 - give each form a reasonably unique css class
269 $this->addClass(CRM_Utils_System
::getClassName($this));
271 $this->assign('snippet', CRM_Utils_Array
::value('snippet', $_GET));
275 * Add one or more css classes to the form.
277 * @param string $className
279 public function addClass($className) {
280 $classes = $this->getAttribute('class');
281 $this->setAttribute('class', ($classes ?
"$classes " : '') . $className);
285 * Register all the standard rules that most forms potentially use.
287 public function registerRules() {
288 static $rules = array(
317 foreach ($rules as $rule) {
318 $this->registerRule($rule, 'callback', $rule, 'CRM_Utils_Rule');
323 * Simple easy to use wrapper around addElement.
325 * Deal with simple validation rules.
327 * @param string $type
328 * @param string $name
329 * @param string $label
330 * @param string|array $attributes (options for select elements)
331 * @param bool $required
332 * @param array $extra
333 * (attributes for select elements).
334 * For datepicker elements this is consistent with the data
335 * from CRM_Utils_Date::getDatePickerExtra
337 * @return HTML_QuickForm_Element
338 * Could be an error object
340 public function &add(
341 $type, $name, $label = '',
342 $attributes = '', $required = FALSE, $extra = NULL
344 // Fudge some extra types that quickform doesn't support
346 if ($type == 'wysiwyg' ||
in_array($type, self
::$html5Types)) {
347 $attributes = ($attributes ?
$attributes : array()) +
array('class' => '');
348 $attributes['class'] = ltrim($attributes['class'] . " crm-form-$type");
349 if ($type == 'wysiwyg' && isset($attributes['preset'])) {
350 $attributes['data-preset'] = $attributes['preset'];
351 unset($attributes['preset']);
353 $type = $type == 'wysiwyg' ?
'textarea' : 'text';
355 // Like select but accepts rich array data (with nesting, colors, icons, etc) as option list.
356 if ($inputType == 'select2') {
358 $options = $attributes;
359 $attributes = $attributes = ($extra ?
$extra : array()) +
array('class' => '');
360 $attributes['class'] = ltrim($attributes['class'] . " crm-select2 crm-form-select2");
361 $attributes['data-select-params'] = json_encode(array('data' => $options, 'multiple' => !empty($attributes['multiple'])));
362 unset($attributes['multiple']);
365 // @see http://wiki.civicrm.org/confluence/display/CRMDOC/crmDatepicker
366 if ($type == 'datepicker') {
367 $attributes = ($attributes ?
$attributes : array());
368 $attributes['data-crm-datepicker'] = json_encode((array) $extra);
371 if ($type == 'select' && is_array($extra)) {
372 // Normalize this property
373 if (!empty($extra['multiple'])) {
374 $extra['multiple'] = 'multiple';
377 unset($extra['multiple']);
379 unset($extra['size'], $extra['maxlength']);
380 // Add placeholder option for select
381 if (isset($extra['placeholder'])) {
382 if ($extra['placeholder'] === TRUE) {
383 $extra['placeholder'] = $required ?
ts('- select -') : ts('- none -');
385 if (($extra['placeholder'] ||
$extra['placeholder'] === '') && empty($extra['multiple']) && is_array($attributes) && !isset($attributes[''])) {
386 $attributes = array('' => $extra['placeholder']) +
$attributes;
390 $element = $this->addElement($type, $name, $label, $attributes, $extra);
391 if (HTML_QuickForm
::isError($element)) {
392 CRM_Core_Error
::fatal(HTML_QuickForm
::errorMessage($element));
395 if ($inputType == 'color') {
396 $this->addRule($name, ts('%1 must contain a color value e.g. #ffffff.', array(1 => $label)), 'regex', '/#[0-9a-fA-F]{6}/');
400 if ($type == 'file') {
401 $error = $this->addRule($name, ts('%1 is a required field.', array(1 => $label)), 'uploadedfile');
404 $error = $this->addRule($name, ts('%1 is a required field.', array(1 => $label)), 'required');
406 if (HTML_QuickForm
::isError($error)) {
407 CRM_Core_Error
::fatal(HTML_QuickForm
::errorMessage($element));
417 * This is called before buildForm. Any pre-processing that
418 * needs to be done for buildForm should be done here.
420 * This is a virtual function and should be redefined if needed.
422 public function preProcess() {
426 * Called after the form is validated.
428 * Any processing of form state etc should be done in this function.
429 * Typically all processing associated with a form should be done
430 * here and relevant state should be stored in the session
432 * This is a virtual function and should be redefined if needed
434 public function postProcess() {
438 * Main process wrapper.
440 * Implemented so that we can call all the hook functions.
442 * @param bool $allowAjax
443 * FIXME: This feels kind of hackish, ideally we would take the json-related code from this function.
444 * and bury it deeper down in the controller
446 public function mainProcess($allowAjax = TRUE) {
447 $this->postProcess();
448 $this->postProcessHook();
450 // Respond with JSON if in AJAX context (also support legacy value '6')
451 if ($allowAjax && !empty($_REQUEST['snippet']) && in_array($_REQUEST['snippet'], array(
452 CRM_Core_Smarty
::PRINT_JSON
,
456 $this->ajaxResponse
['buttonName'] = str_replace('_qf_' . $this->getAttribute('id') . '_', '', $this->controller
->getButtonName());
457 $this->ajaxResponse
['action'] = $this->_action
;
458 if (isset($this->_id
) ||
isset($this->id
)) {
459 $this->ajaxResponse
['id'] = isset($this->id
) ?
$this->id
: $this->_id
;
461 CRM_Core_Page_AJAX
::returnJsonResponse($this->ajaxResponse
);
466 * The postProcess hook is typically called by the framework.
468 * However in a few cases, the form exits or redirects early in which
469 * case it needs to call this function so other modules can do the needful
470 * Calling this function directly should be avoided if possible. In general a
471 * better way is to do setUserContext so the framework does the redirect
473 public function postProcessHook() {
474 CRM_Utils_Hook
::postProcess(get_class($this), $this);
478 * This virtual function is used to build the form.
480 * It replaces the buildForm associated with QuickForm_Page. This allows us to put
481 * preProcess in front of the actual form building routine
483 public function buildQuickForm() {
487 * This virtual function is used to set the default values of various form elements.
490 * reference to the array of default values
492 public function setDefaultValues() {
497 * This is a virtual function that adds group and global rules to the form.
499 * Keeping it distinct from the form to keep code small
500 * and localized in the form building code
502 public function addRules() {
506 * Performs the server side validation.
509 * true if no error found
510 * @throws HTML_QuickForm_Error
512 public function validate() {
513 $error = parent
::validate();
515 $this->validateChainSelectFields();
517 $hookErrors = array();
519 CRM_Utils_Hook
::validateForm(
521 $this->_submitValues
,
527 if (!empty($hookErrors)) {
528 $this->_errors +
= $hookErrors;
531 return (0 == count($this->_errors
));
535 * Core function that builds the form.
537 * We redefine this function here and expect all CRM forms to build their form in the function
540 public function buildForm() {
541 $this->_formBuilt
= TRUE;
545 CRM_Utils_Hook
::preProcess(get_class($this), $this);
547 $this->assign('translatePermission', CRM_Core_Permission
::check('translate CiviCRM'));
550 $this->controller
->_key
&&
551 $this->controller
->_generateQFKey
553 $this->addElement('hidden', 'qfKey', $this->controller
->_key
);
554 $this->assign('qfKey', $this->controller
->_key
);
558 // _generateQFKey suppresses the qfKey generation on form snippets that
559 // are part of other forms, hence we use that to avoid adding entryURL
560 if ($this->controller
->_generateQFKey
&& $this->controller
->_entryURL
) {
561 $this->addElement('hidden', 'entryURL', $this->controller
->_entryURL
);
564 $this->buildQuickForm();
566 $defaults = $this->setDefaultValues();
567 unset($defaults['qfKey']);
569 if (!empty($defaults)) {
570 $this->setDefaults($defaults);
573 // call the form hook
574 // also call the hook function so any modules can set their own custom defaults
575 // the user can do both the form and set default values with this hook
576 CRM_Utils_Hook
::buildForm(get_class($this), $this);
580 //Set html data-attribute to enable warning user of unsaved changes
581 if ($this->unsavedChangesWarn
=== TRUE
582 ||
(!isset($this->unsavedChangesWarn
)
583 && ($this->_action
& CRM_Core_Action
::ADD ||
$this->_action
& CRM_Core_Action
::UPDATE
)
586 $this->setAttribute('data-warn-changes', 'true');
591 * Add default Next / Back buttons.
593 * @param array $params
594 * Array of associative arrays in the order in which the buttons should be
595 * displayed. The associate array has 3 fields: 'type', 'name' and 'isDefault'
596 * The base form class will define a bunch of static arrays for commonly used
599 public function addButtons($params) {
600 $prevnext = $spacing = array();
601 foreach ($params as $button) {
602 $attrs = array('class' => 'crm-form-submit') +
(array) CRM_Utils_Array
::value('js', $button);
604 if (!empty($button['class'])) {
605 $attrs['class'] .= ' ' . $button['class'];
608 if (!empty($button['isDefault'])) {
609 $attrs['class'] .= ' default';
612 if (in_array($button['type'], array('upload', 'next', 'submit', 'done', 'process', 'refresh'))) {
613 $attrs['class'] .= ' validate';
614 $defaultIcon = 'fa-check';
617 $attrs['class'] .= ' cancel';
618 $defaultIcon = $button['type'] == 'back' ?
'fa-chevron-left' : 'fa-times';
621 if ($button['type'] === 'reset') {
622 $prevnext[] = $this->createElement($button['type'], 'reset', $button['name'], $attrs);
625 if (!empty($button['subName'])) {
626 if ($button['subName'] == 'new') {
627 $defaultIcon = 'fa-plus-circle';
629 if ($button['subName'] == 'done') {
630 $defaultIcon = 'fa-check-circle';
632 if ($button['subName'] == 'next') {
633 $defaultIcon = 'fa-chevron-right';
637 if (in_array($button['type'], array('next', 'upload', 'done')) && $button['name'] === ts('Save')) {
638 $attrs['accesskey'] = 'S';
640 $icon = CRM_Utils_Array
::value('icon', $button, $defaultIcon);
642 $attrs['crm-icon'] = $icon;
644 $buttonName = $this->getButtonName($button['type'], CRM_Utils_Array
::value('subName', $button));
645 $prevnext[] = $this->createElement('submit', $buttonName, $button['name'], $attrs);
647 if (!empty($button['isDefault'])) {
648 $this->setDefaultAction($button['type']);
651 // if button type is upload, set the enctype
652 if ($button['type'] == 'upload') {
653 $this->updateAttributes(array('enctype' => 'multipart/form-data'));
654 $this->setMaxFileSize();
657 // hack - addGroup uses an array to express variable spacing, read from the last element
658 $spacing[] = CRM_Utils_Array
::value('spacing', $button, self
::ATTR_SPACING
);
660 $this->addGroup($prevnext, 'buttons', '', $spacing, FALSE);
664 * Getter function for Name.
668 public function getName() {
673 * Getter function for State.
677 public function &getState() {
678 return $this->_state
;
682 * Getter function for StateType.
686 public function getStateType() {
687 return $this->_state
->getType();
691 * Getter function for title.
693 * Should be over-ridden by derived class.
697 public function getTitle() {
698 return $this->_title ?
$this->_title
: ts('ERROR: Title is not Set');
702 * Setter function for title.
704 * @param string $title
705 * The title of the form.
707 public function setTitle($title) {
708 $this->_title
= $title;
712 * Assign billing type id to bltID.
714 * @throws CRM_Core_Exception
716 public function assignBillingType() {
717 $this->_bltID
= CRM_Core_BAO_LocationType
::getBilling();
718 $this->set('bltID', $this->_bltID
);
719 $this->assign('bltID', $this->_bltID
);
723 * This if a front end form function for setting the payment processor.
725 * It would be good to sync it with the back-end function on abstractEditPayment & use one everywhere.
727 * @param bool $is_pay_later_enabled
729 * @throws \CRM_Core_Exception
731 protected function assignPaymentProcessor($is_pay_later_enabled) {
732 $this->_paymentProcessors
= CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors(
733 array(ucfirst($this->_mode
) . 'Mode'),
734 $this->_paymentProcessorIDs
737 if (!empty($this->_paymentProcessors
)) {
738 if ($is_pay_later_enabled) {
739 $this->_paymentProcessors
[0] = CRM_Financial_BAO_PaymentProcessor
::getPayment(0);
741 foreach ($this->_paymentProcessors
as $paymentProcessorID => $paymentProcessorDetail) {
742 if (empty($this->_paymentProcessor
) && $paymentProcessorDetail['is_default'] == 1 ||
(count($this->_paymentProcessors
) == 1)
744 $this->_paymentProcessor
= $paymentProcessorDetail;
745 $this->assign('paymentProcessor', $this->_paymentProcessor
);
746 // Setting this is a bit of a legacy overhang.
747 $this->_paymentObject
= $paymentProcessorDetail['object'];
750 // It's not clear why we set this on the form.
751 $this->set('paymentProcessors', $this->_paymentProcessors
);
754 throw new CRM_Core_Exception(ts('A payment processor configured for this page might be disabled (contact the site administrator for assistance).'));
760 * Format the fields for the payment processor.
762 * In order to pass fields to the payment processor in a consistent way we add some renamed
765 * @param array $fields
769 protected function formatParamsForPaymentProcessor($fields) {
770 // also add location name to the array
771 $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
);
772 $this->_params
["address_name-{$this->_bltID}"] = trim($this->_params
["address_name-{$this->_bltID}"]);
773 // Add additional parameters that the payment processors are used to receiving.
774 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
775 $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}"]);
777 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
778 $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}"]);
781 list($hasAddressField, $addressParams) = CRM_Contribute_BAO_Contribution
::getPaymentProcessorReadyAddressParams($this->_params
, $this->_bltID
);
782 if ($hasAddressField) {
783 $this->_params
= array_merge($this->_params
, $addressParams);
786 $nameFields = array('first_name', 'middle_name', 'last_name');
787 foreach ($nameFields as $name) {
789 if (array_key_exists("billing_$name", $this->_params
)) {
790 $this->_params
[$name] = $this->_params
["billing_{$name}"];
791 $this->_params
['preserveDBName'] = TRUE;
798 * Handle Payment Processor switching for contribution and event registration forms.
800 * This function is shared between contribution & event forms & this is their common class.
802 * However, this should be seen as an in-progress refactor, the end goal being to also align the
803 * backoffice forms that action payments.
805 * This function overlaps assignPaymentProcessor, in a bad way.
807 protected function preProcessPaymentOptions() {
808 $this->_paymentProcessorID
= NULL;
809 if ($this->_paymentProcessors
) {
810 if (!empty($this->_submitValues
)) {
811 $this->_paymentProcessorID
= CRM_Utils_Array
::value('payment_processor_id', $this->_submitValues
);
812 $this->_paymentProcessor
= CRM_Utils_Array
::value($this->_paymentProcessorID
, $this->_paymentProcessors
);
813 $this->set('type', $this->_paymentProcessorID
);
814 $this->set('mode', $this->_mode
);
815 $this->set('paymentProcessor', $this->_paymentProcessor
);
817 // Set default payment processor
819 foreach ($this->_paymentProcessors
as $values) {
820 if (!empty($values['is_default']) ||
count($this->_paymentProcessors
) == 1) {
821 $this->_paymentProcessorID
= $values['id'];
826 if ($this->_paymentProcessorID
827 ||
(isset($this->_submitValues
['payment_processor_id']) && $this->_submitValues
['payment_processor_id'] == 0)
829 CRM_Core_Payment_ProcessorForm
::preProcess($this);
832 $this->_paymentProcessor
= array();
834 CRM_Financial_Form_Payment
::addCreditCardJs($this->_paymentProcessorID
);
836 $this->assign('paymentProcessorID', $this->_paymentProcessorID
);
837 // We save the fact that the profile 'billing' is required on the payment form.
838 // Currently pay-later is the only 'processor' that takes notice of this - but ideally
839 // 1) it would be possible to select the minimum_billing_profile_id for the contribution form
840 // 2) that profile_id would be set on the payment processor
841 // 3) the payment processor would return a billing form that combines these user-configured
842 // minimums with the payment processor minimums. This would lead to fields like 'postal_code'
843 // only being on the form if either the admin has configured it as wanted or the processor
845 $this->assign('billing_profile_id', (CRM_Utils_Array
::value('is_billing_required', $this->_values
) ?
'billing' : ''));
849 * Handle pre approval for processors.
851 * This fits with the flow where a pre-approval is done and then confirmed in the next stage when confirm is hit.
853 * This function is shared between contribution & event forms & this is their common class.
855 * However, this should be seen as an in-progress refactor, the end goal being to also align the
856 * backoffice forms that action payments.
858 * @param array $params
860 protected function handlePreApproval(&$params) {
862 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
863 $params['component'] = 'contribute';
864 $result = $payment->doPreApproval($params);
865 if (empty($result)) {
866 // This could happen, for example, when paypal looks at the button value & decides it is not paypal express.
870 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
871 CRM_Core_Error
::statusBounce(ts('Payment approval failed with message :') . $e->getMessage(), $payment->getCancelUrl($params['qfKey'], CRM_Utils_Array
::value('participant_id', $params)));
874 $this->set('pre_approval_parameters', $result['pre_approval_parameters']);
875 if (!empty($result['redirect_url'])) {
876 CRM_Utils_System
::redirect($result['redirect_url']);
881 * Setter function for options.
883 * @param mixed $options
885 public function setOptions($options) {
886 $this->_options
= $options;
890 * Render form and return contents.
894 public function toSmarty() {
895 $this->preProcessChainSelectFields();
896 $renderer = $this->getRenderer();
897 $this->accept($renderer);
898 $content = $renderer->toArray();
899 $content['formName'] = $this->getName();
901 $content['formClass'] = CRM_Utils_System
::getClassName($this);
906 * Getter function for renderer.
908 * If renderer is not set create one and initialize it.
912 public function &getRenderer() {
913 if (!isset($this->_renderer
)) {
914 $this->_renderer
= CRM_Core_Form_Renderer
::singleton();
916 return $this->_renderer
;
920 * Use the form name to create the tpl file name.
924 public function getTemplateFileName() {
925 $ext = CRM_Extension_System
::singleton()->getMapper();
926 if ($ext->isExtensionClass(CRM_Utils_System
::getClassName($this))) {
927 $filename = $ext->getTemplateName(CRM_Utils_System
::getClassName($this));
928 $tplname = $ext->getTemplatePath(CRM_Utils_System
::getClassName($this)) . DIRECTORY_SEPARATOR
. $filename;
932 CRM_Utils_System
::getClassName($this),
934 '_' => DIRECTORY_SEPARATOR
,
935 '\\' => DIRECTORY_SEPARATOR
,
943 * A wrapper for getTemplateFileName.
945 * This includes calling the hook to prevent us from having to copy & paste the logic of calling the hook.
947 public function getHookedTemplateFileName() {
948 $pageTemplateFile = $this->getTemplateFileName();
949 CRM_Utils_Hook
::alterTemplateFile(get_class($this), $this, 'page', $pageTemplateFile);
950 return $pageTemplateFile;
954 * Default extra tpl file basically just replaces .tpl with .extra.tpl.
956 * i.e. we do not override.
960 public function overrideExtraTemplateFileName() {
965 * Error reporting mechanism.
967 * @param string $message
971 * @param CRM_Core_DAO $dao
972 * A data access object on which we perform a rollback if non - empty.
974 public function error($message, $code = NULL, $dao = NULL) {
976 $dao->query('ROLLBACK');
979 $error = CRM_Core_Error
::singleton();
981 $error->push($code, $message);
985 * Store the variable with the value in the form scope.
987 * @param string $name
988 * Name of the variable.
989 * @param mixed $value
990 * Value of the variable.
992 public function set($name, $value) {
993 $this->controller
->set($name, $value);
997 * Get the variable from the form scope.
999 * @param string $name
1000 * Name of the variable
1004 public function get($name) {
1005 return $this->controller
->get($name);
1009 * Getter for action.
1013 public function getAction() {
1014 return $this->_action
;
1018 * Setter for action.
1020 * @param int $action
1021 * The mode we want to set the form.
1023 public function setAction($action) {
1024 $this->_action
= $action;
1028 * Assign value to name in template.
1030 * @param string $var
1032 * @param mixed $value
1033 * Value of variable.
1035 public function assign($var, $value = NULL) {
1036 self
::$_template->assign($var, $value);
1040 * Assign value to name in template by reference.
1042 * @param string $var
1044 * @param mixed $value
1045 * Value of variable.
1047 public function assign_by_ref($var, &$value) {
1048 self
::$_template->assign_by_ref($var, $value);
1052 * Appends values to template variables.
1054 * @param array|string $tpl_var the template variable name(s)
1055 * @param mixed $value
1056 * The value to append.
1057 * @param bool $merge
1059 public function append($tpl_var, $value = NULL, $merge = FALSE) {
1060 self
::$_template->append($tpl_var, $value, $merge);
1064 * Returns an array containing template variables.
1066 * @param string $name
1070 public function get_template_vars($name = NULL) {
1071 return self
::$_template->get_template_vars($name);
1075 * @param string $name
1078 * @param array $attributes
1079 * @param null $separator
1080 * @param bool $required
1082 * @return HTML_QuickForm_group
1084 public function &addRadio($name, $title, $values, $attributes = array(), $separator = NULL, $required = FALSE) {
1086 $attributes = $attributes ?
$attributes : array();
1087 $allowClear = !empty($attributes['allowClear']);
1088 unset($attributes['allowClear']);
1089 $attributes['id_suffix'] = $name;
1090 foreach ($values as $key => $var) {
1091 $options[] = $this->createElement('radio', NULL, NULL, $var, $key, $attributes);
1093 $group = $this->addGroup($options, $name, $title, $separator);
1095 $this->addRule($name, ts('%1 is a required field.', array(1 => $title)), 'required');
1098 $group->setAttribute('allowClear', TRUE);
1106 * @param bool $allowClear
1107 * @param null $required
1108 * @param array $attributes
1110 public function addYesNo($id, $title, $allowClear = FALSE, $required = NULL, $attributes = array()) {
1111 $attributes +
= array('id_suffix' => $id);
1113 $choice[] = $this->createElement('radio', NULL, '11', ts('Yes'), '1', $attributes);
1114 $choice[] = $this->createElement('radio', NULL, '11', ts('No'), '0', $attributes);
1116 $group = $this->addGroup($choice, $id, $title);
1118 $group->setAttribute('allowClear', TRUE);
1121 $this->addRule($id, ts('%1 is a required field.', array(1 => $title)), 'required');
1129 * @param null $other
1130 * @param null $attributes
1131 * @param null $required
1132 * @param null $javascriptMethod
1133 * @param string $separator
1134 * @param bool $flipValues
1136 public function addCheckBox(
1137 $id, $title, $values, $other = NULL,
1138 $attributes = NULL, $required = NULL,
1139 $javascriptMethod = NULL,
1140 $separator = '<br />', $flipValues = FALSE
1144 if ($javascriptMethod) {
1145 foreach ($values as $key => $var) {
1147 $options[] = $this->createElement('checkbox', $var, NULL, $key, $javascriptMethod);
1150 $options[] = $this->createElement('checkbox', $key, NULL, $var, $javascriptMethod);
1155 foreach ($values as $key => $var) {
1157 $options[] = $this->createElement('checkbox', $var, NULL, $key);
1160 $options[] = $this->createElement('checkbox', $key, NULL, $var);
1165 $this->addGroup($options, $id, $title, $separator);
1168 $this->addElement('text', $id . '_other', ts('Other'), $attributes[$id . '_other']);
1173 ts('%1 is a required field.', array(1 => $title)),
1179 public function resetValues() {
1180 $data = $this->controller
->container();
1181 $data['values'][$this->_name
] = array();
1185 * Simple shell that derived classes can call to add buttons to
1186 * the form with a customized title for the main Submit
1188 * @param string $title
1189 * Title of the main button.
1190 * @param string $nextType
1191 * Button type for the form after processing.
1192 * @param string $backType
1193 * @param bool|string $submitOnce If true, add javascript to next button submit which prevents it from being clicked more than once
1195 public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
1197 if ($backType != NULL) {
1199 'type' => $backType,
1200 'name' => ts('Previous'),
1203 if ($nextType != NULL) {
1204 $nextButton = array(
1205 'type' => $nextType,
1207 'isDefault' => TRUE,
1210 $nextButton['js'] = array('onclick' => "return submitOnce(this,'{$this->_name}','" . ts('Processing') . "');");
1212 $buttons[] = $nextButton;
1214 $this->addButtons($buttons);
1218 * @param string $name
1219 * @param string $from
1221 * @param string $label
1222 * @param string $dateFormat
1223 * @param bool $required
1224 * @param bool $displayTime
1226 public function addDateRange($name, $from = '_from', $to = '_to', $label = 'From:', $dateFormat = 'searchDate', $required = FALSE, $displayTime = FALSE) {
1228 $this->addDateTime($name . $from, $label, $required, array('formatType' => $dateFormat));
1229 $this->addDateTime($name . $to, ts('To:'), $required, array('formatType' => $dateFormat));
1232 $this->addDate($name . $from, $label, $required, array('formatType' => $dateFormat));
1233 $this->addDate($name . $to, ts('To:'), $required, array('formatType' => $dateFormat));
1238 * Based on form action, return a string representing the api action.
1239 * Used by addField method.
1243 private function getApiAction() {
1244 $action = $this->getAction();
1245 if ($action & (CRM_Core_Action
::UPDATE + CRM_Core_Action
::ADD
)) {
1248 if ($action & (CRM_Core_Action
::VIEW + CRM_Core_Action
::BROWSE + CRM_Core_Action
::BASIC + CRM_Core_Action
::ADVANCED + CRM_Core_Action
::PREVIEW
)) {
1251 // If you get this exception try adding more cases above.
1252 throw new Exception("Cannot determine api action for " . get_class($this) . '.' . 'CRM_Core_Action "' . CRM_Core_Action
::description($action) . '" not recognized.');
1256 * Classes extending CRM_Core_Form should implement this method.
1259 public function getDefaultEntity() {
1260 throw new Exception("Cannot determine default entity. " . get_class($this) . " should implement getDefaultEntity().");
1264 * Classes extending CRM_Core_Form should implement this method.
1266 * TODO: Merge with CRM_Core_DAO::buildOptionsContext($context) and add validation.
1269 public function getDefaultContext() {
1270 throw new Exception("Cannot determine default context. " . get_class($this) . " should implement getDefaultContext().");
1274 * Adds a select based on field metadata.
1275 * TODO: This could be even more generic and widget type (select in this case) could also be read from metadata
1276 * Perhaps a method like $form->bind($name) which would look up all metadata for named field
1278 * Field name to go on the form.
1279 * @param array $props
1280 * Mix of html attributes and special properties, namely.
1281 * - entity (api entity name, can usually be inferred automatically from the form class)
1282 * - field (field name - only needed if different from name used on the form)
1283 * - option_url - path to edit this option list - usually retrieved automatically - set to NULL to disable link
1284 * - placeholder - set to NULL to disable
1286 * - context - @see CRM_Core_DAO::buildOptionsContext
1287 * @param bool $required
1288 * @throws CRM_Core_Exception
1289 * @return HTML_QuickForm_Element
1291 public function addSelect($name, $props = array(), $required = FALSE) {
1292 if (!isset($props['entity'])) {
1293 $props['entity'] = $this->getDefaultEntity();
1295 if (!isset($props['field'])) {
1296 $props['field'] = strrpos($name, '[') ?
rtrim(substr($name, 1 +
strrpos($name, '[')), ']') : $name;
1298 if (!isset($props['context'])) {
1300 $props['context'] = $this->getDefaultContext();
1302 // This is not a required param, so we'll ignore if this doesn't exist.
1303 catch (Exception
$e) {}
1305 // Fetch options from the api unless passed explicitly
1306 if (isset($props['options'])) {
1307 $options = $props['options'];
1310 $info = civicrm_api3($props['entity'], 'getoptions', $props);
1311 $options = $info['values'];
1313 if (!array_key_exists('placeholder', $props)) {
1314 $props['placeholder'] = $required ?
ts('- select -') : CRM_Utils_Array
::value('context', $props) == 'search' ?
ts('- any -') : ts('- none -');
1316 // Handle custom field
1317 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
1318 list(, $id) = explode('_', $name);
1319 $label = isset($props['label']) ?
$props['label'] : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', 'label', $id);
1320 $gid = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', 'option_group_id', $id);
1321 if (CRM_Utils_Array
::value('context', $props) != 'search') {
1322 $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);
1327 $info = civicrm_api3($props['entity'], 'getfields');
1328 foreach ($info['values'] as $uniqueName => $fieldSpec) {
1330 $uniqueName === $props['field'] ||
1331 CRM_Utils_Array
::value('name', $fieldSpec) === $props['field'] ||
1332 in_array($props['field'], CRM_Utils_Array
::value('api.aliases', $fieldSpec, array()))
1337 $label = isset($props['label']) ?
$props['label'] : $fieldSpec['title'];
1338 if (CRM_Utils_Array
::value('context', $props) != 'search') {
1339 $props['data-option-edit-path'] = array_key_exists('option_url', $props) ?
$props['option_url'] : CRM_Core_PseudoConstant
::getOptionEditUrl($fieldSpec);
1342 $props['class'] = (isset($props['class']) ?
$props['class'] . ' ' : '') . "crm-select2";
1343 $props['data-api-entity'] = $props['entity'];
1344 $props['data-api-field'] = $props['field'];
1345 CRM_Utils_Array
::remove($props, 'label', 'entity', 'field', 'option_url', 'options', 'context');
1346 return $this->add('select', $name, $label, $options, $required, $props);
1350 * Adds a field based on metadata.
1353 * Field name to go on the form.
1354 * @param array $props
1355 * Mix of html attributes and special properties, namely.
1356 * - entity (api entity name, can usually be inferred automatically from the form class)
1357 * - name (field name - only needed if different from name used on the form)
1358 * - option_url - path to edit this option list - usually retrieved automatically - set to NULL to disable link
1359 * - placeholder - set to NULL to disable
1361 * - context - @see CRM_Core_DAO::buildOptionsContext
1362 * @param bool $required
1363 * @param bool $legacyDate
1364 * Temporary param to facilitate the conversion of fields to use the datepicker in
1365 * a controlled way. To convert the field the jcalendar code needs to be removed from the
1366 * tpl as well. That file is intended to be EOL.
1368 * @throws \CiviCRM_API3_Exception
1369 * @throws \Exception
1370 * @return HTML_QuickForm_Element
1372 public function addField($name, $props = array(), $required = FALSE, $legacyDate = TRUE) {
1374 if (empty($props['context'])) {
1375 $props['context'] = $this->getDefaultContext();
1377 $context = $props['context'];
1379 if (empty($props['entity'])) {
1380 $props['entity'] = $this->getDefaultEntity();
1383 if (empty($props['name'])) {
1384 $props['name'] = strrpos($name, '[') ?
rtrim(substr($name, 1 +
strrpos($name, '[')), ']') : $name;
1387 if (empty($props['action'])) {
1388 $props['action'] = $this->getApiAction();
1391 // Handle custom fields
1392 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
1393 $fieldId = (int) substr($name, 7);
1394 return CRM_Core_BAO_CustomField
::addQuickFormElement($this, $name, $fieldId, $required, $context == 'search', CRM_Utils_Array
::value('label', $props));
1397 // Core field - get metadata.
1398 $fieldSpec = civicrm_api3($props['entity'], 'getfield', $props);
1399 $fieldSpec = $fieldSpec['values'];
1400 $label = CRM_Utils_Array
::value('label', $props, isset($fieldSpec['title']) ?
$fieldSpec['title'] : NULL);
1402 $widget = isset($props['type']) ?
$props['type'] : $fieldSpec['html']['type'];
1403 if ($widget == 'TextArea' && $context == 'search') {
1407 $isSelect = (in_array($widget, array(
1415 // Fetch options from the api unless passed explicitly.
1416 if (isset($props['options'])) {
1417 $options = $props['options'];
1420 $options = isset($fieldSpec['options']) ?
$fieldSpec['options'] : NULL;
1422 if ($context == 'search') {
1424 $props['multiple'] = CRM_Utils_Array
::value('multiple', $props, TRUE);
1427 // Add data for popup link.
1428 if ((!empty($props['option_url']) ||
!array_key_exists('option_url', $props)) && ($context != 'search' && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM'))) {
1429 $props['data-option-edit-path'] = !empty($props['option_url']) ?
$props['option_url'] : CRM_Core_PseudoConstant
::getOptionEditUrl($fieldSpec);
1430 $props['data-api-entity'] = $props['entity'];
1431 $props['data-api-field'] = $props['name'];
1434 $props +
= CRM_Utils_Array
::value('html', $fieldSpec, array());
1435 CRM_Utils_Array
::remove($props, 'entity', 'name', 'context', 'label', 'action', 'type', 'option_url', 'options');
1437 // TODO: refactor switch statement, to separate methods.
1443 //TODO: Autodetect ranges
1444 $props['size'] = isset($props['size']) ?
$props['size'] : 60;
1445 return $this->add(strtolower($widget), $name, $label, $props, $required);
1448 return $this->add('hidden', $name, NULL, $props, $required);
1451 //Set default columns and rows for textarea.
1452 $props['rows'] = isset($props['rows']) ?
$props['rows'] : 4;
1453 $props['cols'] = isset($props['cols']) ?
$props['cols'] : 60;
1454 return $this->add('textarea', $name, $label, $props, $required);
1457 // This is a white list for fields that have been tested with
1458 // date picker. We should be able to remove the other
1460 //TODO: add range support
1461 //TODO: Add date formats
1462 //TODO: Add javascript template for dates.
1463 return $this->addDate($name, $label, $required, $props);
1466 $fieldSpec = CRM_Utils_Date
::addDateMetadataToField($fieldSpec, $fieldSpec);
1467 $attributes = array('format' => $fieldSpec['date_format']);
1468 return $this->add('datepicker', $name, $label, $attributes, $required, $fieldSpec['datepicker']['extra']);
1472 $separator = isset($props['separator']) ?
$props['separator'] : NULL;
1473 unset($props['separator']);
1474 if (!isset($props['allowClear'])) {
1475 $props['allowClear'] = !$required;
1477 return $this->addRadio($name, $label, $options, $props, $separator, $required);
1481 'required' => $required,
1483 'multiple' => $context == 'search',
1485 return $this->addChainSelect($name, $props);
1488 $props['class'] = CRM_Utils_Array
::value('class', $props, 'big') . ' crm-select2';
1489 if (!array_key_exists('placeholder', $props)) {
1490 $props['placeholder'] = $required ?
ts('- select -') : ($context == 'search' ?
ts('- any -') : ts('- none -'));
1492 // TODO: Add and/or option for fields that store multiple values
1493 return $this->add('select', $name, $label, $options, $required, $props);
1495 case 'CheckBoxGroup':
1496 return $this->addCheckBox($name, $label, array_flip($options), $required, $props);
1499 return $this->addRadio($name, $label, $options, $props, NULL, $required);
1502 $text = isset($props['text']) ?
$props['text'] : NULL;
1503 unset($props['text']);
1504 return $this->addElement('checkbox', $name, $label, $text, $props);
1506 //add support for 'Advcheckbox' field
1508 $text = isset($props['text']) ?
$props['text'] : NULL;
1509 unset($props['text']);
1510 return $this->addElement('advcheckbox', $name, $label, $text, $props);
1513 // We should not build upload file in search mode.
1514 if ($context == 'search') {
1517 $file = $this->add('file', $name, $label, $props, $required);
1518 $this->addUploadElement($name);
1521 case 'RichTextEditor':
1522 return $this->add('wysiwyg', $name, $label, $props, $required);
1525 return $this->addEntityRef($name, $label, $props, $required);
1528 return $this->add('password', $name, $label, $props, $required);
1530 // Check datatypes of fields
1534 //case read only fields
1536 throw new Exception("Unsupported html-element " . $widget);
1541 * Add a widget for selecting/editing/creating/copying a profile form
1543 * @param string $name
1544 * HTML form-element name.
1545 * @param string $label
1547 * @param string $allowCoreTypes
1548 * Only present a UFGroup if its group_type includes a subset of $allowCoreTypes; e.g. 'Individual', 'Activity'.
1549 * @param string $allowSubTypes
1550 * Only present a UFGroup if its group_type is compatible with $allowSubypes.
1551 * @param array $entities
1552 * @param bool $default
1554 * @param string $usedFor
1556 public function addProfileSelector($name, $label, $allowCoreTypes, $allowSubTypes, $entities, $default = FALSE, $usedFor = NULL) {
1558 // FIXME: Instead of adhoc serialization, use a single json_encode()
1559 CRM_UF_Page_ProfileEditor
::registerProfileScripts();
1560 CRM_UF_Page_ProfileEditor
::registerSchemas(CRM_Utils_Array
::collect('entity_type', $entities));
1561 $this->add('text', $name, $label, array(
1562 'class' => 'crm-profile-selector',
1563 // Note: client treats ';;' as equivalent to \0, and ';;' works better in HTML
1564 'data-group-type' => CRM_Core_BAO_UFGroup
::encodeGroupType($allowCoreTypes, $allowSubTypes, ';;'),
1565 'data-entities' => json_encode($entities),
1567 'data-default' => $default,
1568 'data-usedfor' => json_encode($usedFor),
1575 public function getRootTitle() {
1582 public function getCompleteTitle() {
1583 return $this->getRootTitle() . $this->getTitle();
1587 * @return CRM_Core_Smarty
1589 public static function &getTemplate() {
1590 return self
::$_template;
1594 * @param $elementName
1596 public function addUploadElement($elementName) {
1597 $uploadNames = $this->get('uploadNames');
1598 if (!$uploadNames) {
1599 $uploadNames = array();
1601 if (is_array($elementName)) {
1602 foreach ($elementName as $name) {
1603 if (!in_array($name, $uploadNames)) {
1604 $uploadNames[] = $name;
1609 if (!in_array($elementName, $uploadNames)) {
1610 $uploadNames[] = $elementName;
1613 $this->set('uploadNames', $uploadNames);
1615 $config = CRM_Core_Config
::singleton();
1616 if (!empty($uploadNames)) {
1617 $this->controller
->addUploadAction($config->customFileUploadDir
, $uploadNames);
1626 public function getVar($name) {
1627 return isset($this->$name) ?
$this->$name : NULL;
1634 public function setVar($name, $value) {
1635 $this->$name = $value;
1642 * Use $this->add('datepicker', ...) instead.
1644 * @param string $name
1645 * Name of the element.
1646 * @param string $label
1647 * Label of the element.
1648 * @param bool $required
1650 * @param array $attributes
1653 public function addDate($name, $label, $required = FALSE, $attributes = NULL) {
1654 if (!empty($attributes['formatType'])) {
1655 // get actual format
1656 $params = array('name' => $attributes['formatType']);
1659 // cache date information
1661 $key = "dateFormat_" . str_replace(' ', '_', $attributes['formatType']);
1662 if (empty($dateFormat[$key])) {
1663 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
1664 $dateFormat[$key] = $values;
1667 $values = $dateFormat[$key];
1670 if ($values['date_format']) {
1671 $attributes['format'] = $values['date_format'];
1674 if (!empty($values['time_format'])) {
1675 $attributes['timeFormat'] = $values['time_format'];
1677 $attributes['startOffset'] = $values['start'];
1678 $attributes['endOffset'] = $values['end'];
1681 $config = CRM_Core_Config
::singleton();
1682 if (empty($attributes['format'])) {
1683 $attributes['format'] = $config->dateInputFormat
;
1686 if (!isset($attributes['startOffset'])) {
1687 $attributes['startOffset'] = 10;
1690 if (!isset($attributes['endOffset'])) {
1691 $attributes['endOffset'] = 10;
1694 $this->add('text', $name, $label, $attributes);
1696 if (!empty($attributes['addTime']) ||
!empty($attributes['timeFormat'])) {
1698 if (!isset($attributes['timeFormat'])) {
1699 $timeFormat = $config->timeInputFormat
;
1702 $timeFormat = $attributes['timeFormat'];
1705 // 1 - 12 hours and 2 - 24 hours, but for jquery widget it is 0 and 1 respectively
1707 $show24Hours = TRUE;
1708 if ($timeFormat == 1) {
1709 $show24Hours = FALSE;
1712 //CRM-6664 -we are having time element name
1713 //in either flat string or an array format.
1714 $elementName = $name . '_time';
1715 if (substr($name, -1) == ']') {
1716 $elementName = substr($name, 0, strlen($name) - 1) . '_time]';
1719 $this->add('text', $elementName, ts('Time'), array('timeFormat' => $show24Hours));
1724 $this->addRule($name, ts('Please select %1', array(1 => $label)), 'required');
1725 if (!empty($attributes['addTime']) && !empty($attributes['addTimeRequired'])) {
1726 $this->addRule($elementName, ts('Please enter a time.'), 'required');
1732 * Function that will add date and time.
1735 * Use $this->add('datepicker', ...) instead.
1737 * @param string $name
1738 * @param string $label
1739 * @param bool $required
1740 * @param null $attributes
1742 public function addDateTime($name, $label, $required = FALSE, $attributes = NULL) {
1743 $addTime = array('addTime' => TRUE);
1744 if (is_array($attributes)) {
1745 $attributes = array_merge($attributes, $addTime);
1748 $attributes = $addTime;
1751 $this->addDate($name, $label, $required, $attributes);
1755 * Add a currency and money element to the form.
1757 * @param string $name
1758 * @param string $label
1759 * @param bool $required
1760 * @param null $attributes
1761 * @param bool $addCurrency
1762 * @param string $currencyName
1763 * @param null $defaultCurrency
1764 * @param bool $freezeCurrency
1766 * @return \HTML_QuickForm_Element
1768 public function addMoney(
1773 $addCurrency = TRUE,
1774 $currencyName = 'currency',
1775 $defaultCurrency = NULL,
1776 $freezeCurrency = FALSE
1778 $element = $this->add('text', $name, $label, $attributes, $required);
1779 $this->addRule($name, ts('Please enter a valid amount.'), 'money');
1782 $ele = $this->addCurrency($currencyName, NULL, TRUE, $defaultCurrency, $freezeCurrency);
1789 * Add currency element to the form.
1791 * @param string $name
1792 * @param null $label
1793 * @param bool $required
1794 * @param string $defaultCurrency
1795 * @param bool $freezeCurrency
1796 * @param bool $setDefaultCurrency
1798 public function addCurrency(
1802 $defaultCurrency = NULL,
1803 $freezeCurrency = FALSE,
1804 $setDefaultCurrency = TRUE
1806 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
1807 $options = array('class' => 'crm-select2 eight');
1809 $currencies = array('' => '') +
$currencies;
1810 $options['placeholder'] = ts('- none -');
1812 $ele = $this->add('select', $name, $label, $currencies, $required, $options);
1813 if ($freezeCurrency) {
1816 if (!$defaultCurrency) {
1817 $config = CRM_Core_Config
::singleton();
1818 $defaultCurrency = $config->defaultCurrency
;
1820 // In some case, setting currency field by default might override the default value
1821 // as encountered in CRM-20527 for batch data entry
1822 if ($setDefaultCurrency) {
1823 $this->setDefaults(array($name => $defaultCurrency));
1828 * Create a single or multiple entity ref field.
1829 * @param string $name
1830 * @param string $label
1831 * @param array $props
1832 * Mix of html and widget properties, including:.
1833 * - select - params to give to select2 widget
1834 * - entity - defaults to contact
1835 * - create - can the user create a new entity on-the-fly?
1836 * Set to TRUE if entity is contact and you want the default profiles,
1837 * or pass in your own set of links. @see CRM_Core_BAO_UFGroup::getCreateLinks for format
1838 * note that permissions are checked automatically
1839 * - api - array of settings for the getlist api wrapper
1840 * note that it accepts a 'params' setting which will be passed to the underlying api
1841 * - placeholder - string
1843 * - class, etc. - other html properties
1844 * @param bool $required
1846 * @return HTML_QuickForm_Element
1848 public function addEntityRef($name, $label = '', $props = array(), $required = FALSE) {
1849 require_once "api/api.php";
1850 $config = CRM_Core_Config
::singleton();
1851 // Default properties
1852 $props['api'] = CRM_Utils_Array
::value('api', $props, array());
1853 $props['entity'] = _civicrm_api_get_entity_name_from_camel(CRM_Utils_Array
::value('entity', $props, 'contact'));
1854 $props['class'] = ltrim(CRM_Utils_Array
::value('class', $props, '') . ' crm-form-entityref');
1856 if ($props['entity'] == 'contact' && isset($props['create']) && !(CRM_Core_Permission
::check('edit all contacts') || CRM_Core_Permission
::check('add contacts'))) {
1857 unset($props['create']);
1860 $props['placeholder'] = CRM_Utils_Array
::value('placeholder', $props, $required ?
ts('- select %1 -', array(1 => ts(str_replace('_', ' ', $props['entity'])))) : ts('- none -'));
1862 $defaults = array();
1863 if (!empty($props['multiple'])) {
1864 $defaults['multiple'] = TRUE;
1866 $props['select'] = CRM_Utils_Array
::value('select', $props, array()) +
$defaults;
1868 $this->formatReferenceFieldAttributes($props);
1869 return $this->add('text', $name, $label, $props, $required);
1875 private function formatReferenceFieldAttributes(&$props) {
1876 $props['data-select-params'] = json_encode($props['select']);
1877 $props['data-api-params'] = $props['api'] ?
json_encode($props['api']) : NULL;
1878 $props['data-api-entity'] = $props['entity'];
1879 if (!empty($props['create'])) {
1880 $props['data-create-links'] = json_encode($props['create']);
1882 CRM_Utils_Array
::remove($props, 'multiple', 'select', 'api', 'entity', 'create');
1886 * Convert all date fields within the params to mysql date ready for the
1887 * BAO layer. In this case fields are checked against the $_datefields defined for the form
1888 * and if time is defined it is incorporated
1890 * @param array $params
1891 * Input params from the form.
1893 * @todo it would probably be better to work on $this->_params than a passed array
1894 * @todo standardise the format which dates are passed to the BAO layer in & remove date
1897 public function convertDateFieldsToMySQL(&$params) {
1898 foreach ($this->_dateFields
as $fieldName => $specs) {
1899 if (!empty($params[$fieldName])) {
1900 $params[$fieldName] = CRM_Utils_Date
::isoToMysql(
1901 CRM_Utils_Date
::processDate(
1902 $params[$fieldName],
1903 CRM_Utils_Array
::value("{$fieldName}_time", $params), TRUE)
1907 if (isset($specs['default'])) {
1908 $params[$fieldName] = date('YmdHis', strtotime($specs['default']));
1915 * @param $elementName
1917 public function removeFileRequiredRules($elementName) {
1918 $this->_required
= array_diff($this->_required
, array($elementName));
1919 if (isset($this->_rules
[$elementName])) {
1920 foreach ($this->_rules
[$elementName] as $index => $ruleInfo) {
1921 if ($ruleInfo['type'] == 'uploadedfile') {
1922 unset($this->_rules
[$elementName][$index]);
1925 if (empty($this->_rules
[$elementName])) {
1926 unset($this->_rules
[$elementName]);
1932 * Function that can be defined in Form to override or.
1933 * perform specific action on cancel action
1935 public function cancelAction() {
1939 * Helper function to verify that required fields have been filled.
1941 * Typically called within the scope of a FormRule function
1943 * @param array $fields
1944 * @param array $values
1945 * @param array $errors
1947 public static function validateMandatoryFields($fields, $values, &$errors) {
1948 foreach ($fields as $name => $fld) {
1949 if (!empty($fld['is_required']) && CRM_Utils_System
::isNull(CRM_Utils_Array
::value($name, $values))) {
1950 $errors[$name] = ts('%1 is a required field.', array(1 => $fld['title']));
1956 * Get contact if for a form object. Prioritise
1957 * - cid in URL if 0 (on behalf on someoneelse)
1958 * (@todo consider setting a variable if onbehalf for clarity of downstream 'if's
1959 * - logged in user id if it matches the one in the cid in the URL
1960 * - contact id validated from a checksum from a checksum
1961 * - cid from the url if the caller has ACL permission to view
1962 * - fallback is logged in user (or ? NULL if no logged in user) (@todo wouldn't 0 be more intuitive?)
1966 protected function setContactID() {
1967 $tempID = CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
1968 if (isset($this->_params
) && !empty($this->_params
['select_contact_id'])) {
1969 $tempID = $this->_params
['select_contact_id'];
1971 if (isset($this->_params
, $this->_params
[0]) && !empty($this->_params
[0]['select_contact_id'])) {
1972 // event form stores as an indexed array, contribution form not so much...
1973 $tempID = $this->_params
[0]['select_contact_id'];
1976 // force to ignore the authenticated user
1977 if ($tempID === '0' ||
$tempID === 0) {
1978 // we set the cid on the form so that this will be retained for the Confirm page
1979 // in the multi-page form & prevent us returning the $userID when this is called
1981 // we don't really need to set it when $tempID is set because the params have that stored
1982 $this->set('cid', 0);
1983 CRM_Core_Resources
::singleton()->addVars('coreForm', array('contact_id' => (int) $tempID));
1984 return (int) $tempID;
1987 $userID = $this->getLoggedInUserContactID();
1989 if (!is_null($tempID) && $tempID === $userID) {
1990 CRM_Core_Resources
::singleton()->addVars('coreForm', array('contact_id' => (int) $tempID));
1991 return (int) $userID;
1994 //check if this is a checksum authentication
1995 $userChecksum = CRM_Utils_Request
::retrieve('cs', 'String', $this);
1996 if ($userChecksum) {
1997 //check for anonymous user.
1998 $validUser = CRM_Contact_BAO_Contact_Utils
::validChecksum($tempID, $userChecksum);
2000 CRM_Core_Resources
::singleton()->addVars('coreForm', array('contact_id' => (int) $tempID));
2001 CRM_Core_Resources
::singleton()->addVars('coreForm', array('checksum' => (int) $tempID));
2005 // check if user has permission, CRM-12062
2006 elseif ($tempID && CRM_Contact_BAO_Contact_Permission
::allow($tempID)) {
2007 CRM_Core_Resources
::singleton()->addVars('coreForm', array('contact_id' => (int) $tempID));
2010 if (is_numeric($userID)) {
2011 CRM_Core_Resources
::singleton()->addVars('coreForm', array('contact_id' => (int) $userID));
2013 return is_numeric($userID) ?
$userID : NULL;
2017 * Get the contact id that the form is being submitted for.
2021 public function getContactID() {
2022 return $this->setContactID();
2026 * Get the contact id of the logged in user.
2028 public function getLoggedInUserContactID() {
2029 // check if the user is logged in and has a contact ID
2030 $session = CRM_Core_Session
::singleton();
2031 return $session->get('userID');
2035 * Add autoselector field -if user has permission to view contacts
2036 * If adding this to a form you also need to add to the tpl e.g
2038 * {if !empty($selectable)}
2039 * <div class="crm-summary-row">
2040 * <div class="crm-label">{$form.select_contact.label}</div>
2041 * <div class="crm-content">
2042 * {$form.select_contact.html}
2047 * @param array $profiles
2048 * Ids of profiles that are on the form (to be autofilled).
2049 * @param array $autoCompleteField
2053 * - url (for ajax lookup)
2055 * @todo add data attributes so we can deal with multiple instances on a form
2057 public function addAutoSelector($profiles = array(), $autoCompleteField = array()) {
2058 $autoCompleteField = array_merge(array(
2059 'id_field' => 'select_contact_id',
2060 'placeholder' => ts('Select someone else ...'),
2061 'show_hide' => TRUE,
2062 'api' => array('params' => array('contact_type' => 'Individual')),
2063 ), $autoCompleteField);
2065 if ($this->canUseAjaxContactLookups()) {
2066 $this->assign('selectable', $autoCompleteField['id_field']);
2067 $this->addEntityRef($autoCompleteField['id_field'], NULL, array(
2068 'placeholder' => $autoCompleteField['placeholder'],
2069 'api' => $autoCompleteField['api'],
2072 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/AlternateContactSelector.js', 1, 'html-header')
2074 'form' => array('autocompletes' => $autoCompleteField),
2075 'ids' => array('profile' => $profiles),
2082 public function canUseAjaxContactLookups() {
2083 if (0 < (civicrm_api3('contact', 'getcount', array('check_permissions' => 1))) &&
2084 CRM_Core_Permission
::check(array(array('access AJAX API', 'access CiviCRM')))
2091 * Add the options appropriate to cid = zero - ie. autocomplete
2093 * @todo there is considerable code duplication between the contribution forms & event forms. It is apparent
2094 * that small pieces of duplication are not being refactored into separate functions because their only shared parent
2095 * is this form. Inserting a class FrontEndForm.php between the contribution & event & this class would allow functions like this
2096 * and a dozen other small ones to be refactored into a shared parent with the reduction of much code duplication
2098 * @param $onlinePaymentProcessorEnabled
2100 public function addCIDZeroOptions($onlinePaymentProcessorEnabled) {
2101 $this->assign('nocid', TRUE);
2102 $profiles = array();
2103 if ($this->_values
['custom_pre_id']) {
2104 $profiles[] = $this->_values
['custom_pre_id'];
2106 if ($this->_values
['custom_post_id']) {
2107 $profiles = array_merge($profiles, (array) $this->_values
['custom_post_id']);
2109 if ($onlinePaymentProcessorEnabled) {
2110 $profiles[] = 'billing';
2112 if (!empty($this->_values
)) {
2113 $this->addAutoSelector($profiles);
2118 * Set default values on form for given contact (or no contact defaults)
2120 * @param mixed $profile_id
2121 * (can be id, or profile name).
2122 * @param int $contactID
2126 public function getProfileDefaults($profile_id = 'Billing', $contactID = NULL) {
2128 $defaults = civicrm_api3('profile', 'getsingle', array(
2129 'profile_id' => (array) $profile_id,
2130 'contact_id' => $contactID,
2134 catch (Exception
$e) {
2135 // the try catch block gives us silent failure -not 100% sure this is a good idea
2136 // as silent failures are often worse than noisy ones
2142 * Sets form attribute.
2145 public function preventAjaxSubmit() {
2146 $this->setAttribute('data-no-ajax-submit', 'true');
2150 * Sets form attribute.
2153 public function allowAjaxSubmit() {
2154 $this->removeAttribute('data-no-ajax-submit');
2158 * Sets page title based on entity and action.
2159 * @param string $entityLabel
2161 public function setPageTitle($entityLabel) {
2162 switch ($this->_action
) {
2163 case CRM_Core_Action
::ADD
:
2164 CRM_Utils_System
::setTitle(ts('New %1', array(1 => $entityLabel)));
2167 case CRM_Core_Action
::UPDATE
:
2168 CRM_Utils_System
::setTitle(ts('Edit %1', array(1 => $entityLabel)));
2171 case CRM_Core_Action
::VIEW
:
2172 case CRM_Core_Action
::PREVIEW
:
2173 CRM_Utils_System
::setTitle(ts('View %1', array(1 => $entityLabel)));
2176 case CRM_Core_Action
::DELETE
:
2177 CRM_Utils_System
::setTitle(ts('Delete %1', array(1 => $entityLabel)));
2183 * Create a chain-select target field. All settings are optional; the defaults usually work.
2185 * @param string $elementName
2186 * @param array $settings
2188 * @return HTML_QuickForm_Element
2190 public function addChainSelect($elementName, $settings = array()) {
2191 $props = $settings +
= array(
2192 'control_field' => str_replace(array('state_province', 'StateProvince', 'county', 'County'), array(
2198 'data-callback' => strpos($elementName, 'rovince') ?
'civicrm/ajax/jqState' : 'civicrm/ajax/jqCounty',
2199 'label' => strpos($elementName, 'rovince') ?
ts('State/Province') : ts('County'),
2200 'data-empty-prompt' => strpos($elementName, 'rovince') ?
ts('Choose country first') : ts('Choose state first'),
2201 'data-none-prompt' => ts('- N/A -'),
2202 'multiple' => FALSE,
2203 'required' => FALSE,
2204 'placeholder' => empty($settings['required']) ?
ts('- none -') : ts('- select -'),
2206 CRM_Utils_Array
::remove($props, 'label', 'required', 'control_field', 'context');
2207 $props['class'] = (empty($props['class']) ?
'' : "{$props['class']} ") . 'crm-select2';
2208 $props['data-select-prompt'] = $props['placeholder'];
2209 $props['data-name'] = $elementName;
2211 $this->_chainSelectFields
[$settings['control_field']] = $elementName;
2213 // Passing NULL instead of an array of options
2214 // CRM-15225 - normally QF will reject any selected values that are not part of the field's options, but due to a
2215 // quirk in our patched version of HTML_QuickForm_select, this doesn't happen if the options are NULL
2216 // which seems a bit dirty but it allows our dynamically-popuplated select element to function as expected.
2217 return $this->add('select', $elementName, $settings['label'], NULL, $settings['required'], $props);
2221 * Add actions menu to results form.
2223 * @param array $tasks
2225 public function addTaskMenu($tasks) {
2226 if (is_array($tasks) && !empty($tasks)) {
2227 // Set constants means this will always load with an empty value, not reloading any submitted value.
2228 // This is appropriate as it is a pseudofield.
2229 $this->setConstants(array('task' => ''));
2230 $this->assign('taskMetaData', $tasks);
2231 $select = $this->add('select', 'task', NULL, array('' => ts('Actions')), FALSE, array(
2232 'class' => 'crm-select2 crm-action-menu fa-check-circle-o huge crm-search-result-actions')
2234 foreach ($tasks as $key => $task) {
2235 $attributes = array();
2236 if (isset($task['data'])) {
2237 foreach ($task['data'] as $dataKey => $dataValue) {
2238 $attributes['data-' . $dataKey] = $dataValue;
2241 $select->addOption($task['title'], $key, $attributes);
2243 if (empty($this->_actionButtonName
)) {
2244 $this->_actionButtonName
= $this->getButtonName('next', 'action');
2246 $this->assign('actionButtonName', $this->_actionButtonName
);
2247 $this->add('submit', $this->_actionButtonName
, ts('Go'), array('class' => 'hiddenElement crm-search-go-button'));
2249 // Radio to choose "All items" or "Selected items only"
2250 $selectedRowsRadio = $this->addElement('radio', 'radio_ts', NULL, '', 'ts_sel', array('checked' => 'checked'));
2251 $allRowsRadio = $this->addElement('radio', 'radio_ts', NULL, '', 'ts_all');
2252 $this->assign('ts_sel_id', $selectedRowsRadio->_attributes
['id']);
2253 $this->assign('ts_all_id', $allRowsRadio->_attributes
['id']);
2255 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header');
2260 * Set options and attributes for chain select fields based on the controlling field's value
2262 private function preProcessChainSelectFields() {
2263 foreach ($this->_chainSelectFields
as $control => $target) {
2264 // The 'target' might get missing if extensions do removeElement() in a form hook.
2265 if ($this->elementExists($target)) {
2266 $targetField = $this->getElement($target);
2267 $targetType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ?
'county' : 'stateProvince';
2269 // If the control field is on the form, setup chain-select and dynamically populate options
2270 if ($this->elementExists($control)) {
2271 $controlField = $this->getElement($control);
2272 $controlType = $targetType == 'county' ?
'stateProvince' : 'country';
2274 $targetField->setAttribute('class', $targetField->getAttribute('class') . ' crm-chain-select-target');
2276 $css = (string) $controlField->getAttribute('class');
2277 $controlField->updateAttributes(array(
2278 'class' => ($css ?
"$css " : 'crm-select2 ') . 'crm-chain-select-control',
2279 'data-target' => $target,
2281 $controlValue = $controlField->getValue();
2282 if ($controlValue) {
2283 $options = CRM_Core_BAO_Location
::getChainSelectValues($controlValue, $controlType, TRUE);
2285 $targetField->setAttribute('placeholder', $targetField->getAttribute('data-none-prompt'));
2289 $targetField->setAttribute('placeholder', $targetField->getAttribute('data-empty-prompt'));
2290 $targetField->setAttribute('disabled', 'disabled');
2293 // Control field not present - fall back to loading default options
2295 $options = CRM_Core_PseudoConstant
::$targetType();
2297 if (!$targetField->getAttribute('multiple')) {
2298 $options = array('' => $targetField->getAttribute('placeholder')) +
$options;
2299 $targetField->removeAttribute('placeholder');
2301 $targetField->_options
= array();
2302 $targetField->loadArray($options);
2308 * Validate country / state / county match and suppress unwanted "required" errors
2310 private function validateChainSelectFields() {
2311 foreach ($this->_chainSelectFields
as $control => $target) {
2312 if ($this->elementExists($control) && $this->elementExists($target)) {
2313 $controlValue = (array) $this->getElementValue($control);
2314 $targetField = $this->getElement($target);
2315 $controlType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ?
'stateProvince' : 'country';
2316 $targetValue = array_filter((array) $targetField->getValue());
2317 if ($targetValue ||
$this->getElementError($target)) {
2318 $options = CRM_Core_BAO_Location
::getChainSelectValues($controlValue, $controlType, TRUE);
2320 if (!array_intersect($targetValue, array_keys($options))) {
2321 $this->setElementError($target, $controlType == 'country' ?
ts('State/Province does not match the selected Country') : ts('County does not match the selected State/Province'));
2323 } // Suppress "required" error for field if it has no options
2324 elseif (!$options) {
2325 $this->setElementError($target, NULL);
2333 * Assign billing name to the template.
2335 * @param array $params
2336 * Form input params, default to $this->_params.
2340 public function assignBillingName($params = array()) {
2342 if (empty($params)) {
2343 $params = $this->_params
;
2345 if (!empty($params['billing_first_name'])) {
2346 $name = $params['billing_first_name'];
2349 if (!empty($params['billing_middle_name'])) {
2350 $name .= " {$params['billing_middle_name']}";
2353 if (!empty($params['billing_last_name'])) {
2354 $name .= " {$params['billing_last_name']}";
2356 $name = trim($name);
2357 $this->assign('billingName', $name);