3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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(
223 * Constructor for the basic form page.
225 * We should not use QuickForm directly. This class provides a lot
226 * of default convenient functions, rules and buttons
228 * @param object $state
229 * State associated with this form.
230 * @param \const|\enum|int $action The mode the form is operating in (None/Create/View/Update/Delete)
231 * @param string $method
232 * The type of http method used (GET/POST).
233 * @param string $name
234 * The name of the form if different from class name.
236 * @return \CRM_Core_Form
238 public function __construct(
240 $action = CRM_Core_Action
::NONE
,
246 $this->_name
= $name;
249 // CRM-15153 - FIXME this name translates to a DOM id and is not always unique!
250 $this->_name
= CRM_Utils_String
::getClassName(CRM_Utils_System
::getClassName($this));
253 parent
::__construct($this->_name
, $method);
255 $this->_state
=& $state;
257 $this->_state
->setName($this->_name
);
259 $this->_action
= (int) $action;
261 $this->registerRules();
263 // let the constructor initialize this, should happen only once
264 if (!isset(self
::$_template)) {
265 self
::$_template = CRM_Core_Smarty
::singleton();
267 // Workaround for CRM-15153 - give each form a reasonably unique css class
268 $this->addClass(CRM_Utils_System
::getClassName($this));
270 $this->assign('snippet', CRM_Utils_Array
::value('snippet', $_GET));
274 * Generate ID for some reason & purpose that is unknown & undocumented.
276 public static function generateID() {
280 * Add one or more css classes to the form.
282 * @param string $className
284 public function addClass($className) {
285 $classes = $this->getAttribute('class');
286 $this->setAttribute('class', ($classes ?
"$classes " : '') . $className);
290 * Register all the standard rules that most forms potentially use.
292 public function registerRules() {
293 static $rules = array(
322 foreach ($rules as $rule) {
323 $this->registerRule($rule, 'callback', $rule, 'CRM_Utils_Rule');
328 * Simple easy to use wrapper around addElement.
330 * Deal with simple validation rules.
332 * @param string $type
333 * @param string $name
334 * @param string $label
335 * @param string|array $attributes (options for select elements)
336 * @param bool $required
337 * @param array $extra
338 * (attributes for select elements).
340 * @return HTML_QuickForm_Element
341 * Could be an error object
343 public function &add(
344 $type, $name, $label = '',
345 $attributes = '', $required = FALSE, $extra = NULL
347 // Fudge some extra types that quickform doesn't support
348 if ($type == 'wysiwyg' ||
in_array($type, self
::$html5Types)) {
349 $attributes = ($attributes ?
$attributes : array()) +
array('class' => '');
350 $attributes['class'] = ltrim($attributes['class'] . " crm-form-$type");
351 if ($type == 'wysiwyg' && isset($attributes['preset'])) {
352 $attributes['data-preset'] = $attributes['preset'];
353 unset($attributes['preset']);
355 $type = $type == 'wysiwyg' ?
'textarea' : 'text';
357 // @see http://wiki.civicrm.org/confluence/display/CRMDOC/crmDatepicker
358 if ($type == 'datepicker') {
359 $attributes = ($attributes ?
$attributes : array());
360 $attributes['data-crm-datepicker'] = json_encode((array) $extra);
363 if ($type == 'select' && is_array($extra)) {
364 // Normalize this property
365 if (!empty($extra['multiple'])) {
366 $extra['multiple'] = 'multiple';
369 unset($extra['multiple']);
371 unset($extra['size'], $extra['maxlength']);
372 // Add placeholder option for select
373 if (isset($extra['placeholder'])) {
374 if ($extra['placeholder'] === TRUE) {
375 $extra['placeholder'] = $required ?
ts('- select -') : ts('- none -');
377 if (($extra['placeholder'] ||
$extra['placeholder'] === '') && empty($extra['multiple']) && is_array($attributes) && !isset($attributes[''])) {
378 $attributes = array('' => $extra['placeholder']) +
$attributes;
382 $element = $this->addElement($type, $name, $label, $attributes, $extra);
383 if (HTML_QuickForm
::isError($element)) {
384 CRM_Core_Error
::fatal(HTML_QuickForm
::errorMessage($element));
388 if ($type == 'file') {
389 $error = $this->addRule($name, ts('%1 is a required field.', array(1 => $label)), 'uploadedfile');
392 $error = $this->addRule($name, ts('%1 is a required field.', array(1 => $label)), 'required');
394 if (HTML_QuickForm
::isError($error)) {
395 CRM_Core_Error
::fatal(HTML_QuickForm
::errorMessage($element));
405 * This is called before buildForm. Any pre-processing that
406 * needs to be done for buildForm should be done here.
408 * This is a virtual function and should be redefined if needed.
410 public function preProcess() {
414 * Called after the form is validated.
416 * Any processing of form state etc should be done in this function.
417 * Typically all processing associated with a form should be done
418 * here and relevant state should be stored in the session
420 * This is a virtual function and should be redefined if needed
422 public function postProcess() {
426 * Main process wrapper.
428 * Implemented so that we can call all the hook functions.
430 * @param bool $allowAjax
431 * FIXME: This feels kind of hackish, ideally we would take the json-related code from this function.
432 * and bury it deeper down in the controller
434 public function mainProcess($allowAjax = TRUE) {
435 $this->postProcess();
436 $this->postProcessHook();
438 // Respond with JSON if in AJAX context (also support legacy value '6')
439 if ($allowAjax && !empty($_REQUEST['snippet']) && in_array($_REQUEST['snippet'], array(
440 CRM_Core_Smarty
::PRINT_JSON
,
444 $this->ajaxResponse
['buttonName'] = str_replace('_qf_' . $this->getAttribute('id') . '_', '', $this->controller
->getButtonName());
445 $this->ajaxResponse
['action'] = $this->_action
;
446 if (isset($this->_id
) ||
isset($this->id
)) {
447 $this->ajaxResponse
['id'] = isset($this->id
) ?
$this->id
: $this->_id
;
449 CRM_Core_Page_AJAX
::returnJsonResponse($this->ajaxResponse
);
454 * The postProcess hook is typically called by the framework.
456 * However in a few cases, the form exits or redirects early in which
457 * case it needs to call this function so other modules can do the needful
458 * Calling this function directly should be avoided if possible. In general a
459 * better way is to do setUserContext so the framework does the redirect
461 public function postProcessHook() {
462 CRM_Utils_Hook
::postProcess(get_class($this), $this);
466 * This virtual function is used to build the form.
468 * It replaces the buildForm associated with QuickForm_Page. This allows us to put
469 * preProcess in front of the actual form building routine
471 public function buildQuickForm() {
475 * This virtual function is used to set the default values of various form elements.
478 * reference to the array of default values
480 public function setDefaultValues() {
485 * This is a virtual function that adds group and global rules to the form.
487 * Keeping it distinct from the form to keep code small
488 * and localized in the form building code
490 public function addRules() {
494 * Performs the server side validation.
497 * true if no error found
498 * @throws HTML_QuickForm_Error
500 public function validate() {
501 $error = parent
::validate();
503 $this->validateChainSelectFields();
505 $hookErrors = array();
507 CRM_Utils_Hook
::validateForm(
509 $this->_submitValues
,
515 if (!empty($hookErrors)) {
516 $this->_errors +
= $hookErrors;
519 return (0 == count($this->_errors
));
523 * Core function that builds the form.
525 * We redefine this function here and expect all CRM forms to build their form in the function
528 public function buildForm() {
529 $this->_formBuilt
= TRUE;
533 CRM_Utils_Hook
::preProcess(get_class($this), $this);
535 $this->assign('translatePermission', CRM_Core_Permission
::check('translate CiviCRM'));
538 $this->controller
->_key
&&
539 $this->controller
->_generateQFKey
541 $this->addElement('hidden', 'qfKey', $this->controller
->_key
);
542 $this->assign('qfKey', $this->controller
->_key
);
546 // _generateQFKey suppresses the qfKey generation on form snippets that
547 // are part of other forms, hence we use that to avoid adding entryURL
548 if ($this->controller
->_generateQFKey
&& $this->controller
->_entryURL
) {
549 $this->addElement('hidden', 'entryURL', $this->controller
->_entryURL
);
552 $this->buildQuickForm();
554 $defaults = $this->setDefaultValues();
555 unset($defaults['qfKey']);
557 if (!empty($defaults)) {
558 $this->setDefaults($defaults);
561 // call the form hook
562 // also call the hook function so any modules can set their own custom defaults
563 // the user can do both the form and set default values with this hook
564 CRM_Utils_Hook
::buildForm(get_class($this), $this);
568 //Set html data-attribute to enable warning user of unsaved changes
569 if ($this->unsavedChangesWarn
=== TRUE
570 ||
(!isset($this->unsavedChangesWarn
)
571 && ($this->_action
& CRM_Core_Action
::ADD ||
$this->_action
& CRM_Core_Action
::UPDATE
)
574 $this->setAttribute('data-warn-changes', 'true');
579 * Add default Next / Back buttons.
581 * @param array $params
582 * Array of associative arrays in the order in which the buttons should be
583 * displayed. The associate array has 3 fields: 'type', 'name' and 'isDefault'
584 * The base form class will define a bunch of static arrays for commonly used
587 public function addButtons($params) {
588 $prevnext = $spacing = array();
589 foreach ($params as $button) {
590 $attrs = array('class' => 'crm-form-submit') +
(array) CRM_Utils_Array
::value('js', $button);
592 if (!empty($button['class'])) {
593 $attrs['class'] .= ' ' . $button['class'];
596 if (!empty($button['isDefault'])) {
597 $attrs['class'] .= ' default';
600 if (in_array($button['type'], array('upload', 'next', 'submit', 'done', 'process', 'refresh'))) {
601 $attrs['class'] .= ' validate';
602 $defaultIcon = 'fa-check';
605 $attrs['class'] .= ' cancel';
606 $defaultIcon = $button['type'] == 'back' ?
'fa-chevron-left' : 'fa-times';
609 if ($button['type'] === 'reset') {
610 $prevnext[] = $this->createElement($button['type'], 'reset', $button['name'], $attrs);
613 if (!empty($button['subName'])) {
614 if ($button['subName'] == 'new') {
615 $defaultIcon = 'fa-plus-circle';
617 if ($button['subName'] == 'done') {
618 $defaultIcon = 'fa-check-circle';
620 if ($button['subName'] == 'next') {
621 $defaultIcon = 'fa-chevron-right';
625 if (in_array($button['type'], array('next', 'upload', 'done')) && $button['name'] === ts('Save')) {
626 $attrs['accesskey'] = 'S';
628 $icon = CRM_Utils_Array
::value('icon', $button, $defaultIcon);
630 $attrs['crm-icon'] = $icon;
632 $buttonName = $this->getButtonName($button['type'], CRM_Utils_Array
::value('subName', $button));
633 $prevnext[] = $this->createElement('submit', $buttonName, $button['name'], $attrs);
635 if (!empty($button['isDefault'])) {
636 $this->setDefaultAction($button['type']);
639 // if button type is upload, set the enctype
640 if ($button['type'] == 'upload') {
641 $this->updateAttributes(array('enctype' => 'multipart/form-data'));
642 $this->setMaxFileSize();
645 // hack - addGroup uses an array to express variable spacing, read from the last element
646 $spacing[] = CRM_Utils_Array
::value('spacing', $button, self
::ATTR_SPACING
);
648 $this->addGroup($prevnext, 'buttons', '', $spacing, FALSE);
652 * Getter function for Name.
656 public function getName() {
661 * Getter function for State.
665 public function &getState() {
666 return $this->_state
;
670 * Getter function for StateType.
674 public function getStateType() {
675 return $this->_state
->getType();
679 * Getter function for title.
681 * Should be over-ridden by derived class.
685 public function getTitle() {
686 return $this->_title ?
$this->_title
: ts('ERROR: Title is not Set');
690 * Setter function for title.
692 * @param string $title
693 * The title of the form.
695 public function setTitle($title) {
696 $this->_title
= $title;
700 * Assign billing type id to bltID.
702 * @throws CRM_Core_Exception
704 public function assignBillingType() {
705 $this->_bltID
= CRM_Core_BAO_LocationType
::getBilling();
706 $this->set('bltID', $this->_bltID
);
707 $this->assign('bltID', $this->_bltID
);
711 * This if a front end form function for setting the payment processor.
713 * It would be good to sync it with the back-end function on abstractEditPayment & use one everywhere.
715 * @param bool $is_pay_later_enabled
717 * @throws \CRM_Core_Exception
719 protected function assignPaymentProcessor($is_pay_later_enabled) {
720 $this->_paymentProcessors
= CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors(
721 array(ucfirst($this->_mode
) . 'Mode'),
722 $this->_paymentProcessorIDs
725 if (!empty($this->_paymentProcessors
)) {
726 if ($is_pay_later_enabled) {
727 $this->_paymentProcessors
[0] = CRM_Financial_BAO_PaymentProcessor
::getPayment(0);
729 foreach ($this->_paymentProcessors
as $paymentProcessorID => $paymentProcessorDetail) {
730 if (empty($this->_paymentProcessor
) && $paymentProcessorDetail['is_default'] == 1 ||
(count($this->_paymentProcessors
) == 1)
732 $this->_paymentProcessor
= $paymentProcessorDetail;
733 $this->assign('paymentProcessor', $this->_paymentProcessor
);
734 // Setting this is a bit of a legacy overhang.
735 $this->_paymentObject
= $paymentProcessorDetail['object'];
738 // It's not clear why we set this on the form.
739 $this->set('paymentProcessors', $this->_paymentProcessors
);
742 throw new CRM_Core_Exception(ts('A payment processor configured for this page might be disabled (contact the site administrator for assistance).'));
748 * Format the fields for the payment processor.
750 * In order to pass fields to the payment processor in a consistent way we add some renamed
753 * @param array $fields
757 protected function formatParamsForPaymentProcessor($fields) {
758 // also add location name to the array
759 $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
);
760 $this->_params
["address_name-{$this->_bltID}"] = trim($this->_params
["address_name-{$this->_bltID}"]);
761 // Add additional parameters that the payment processors are used to receiving.
762 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
763 $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}"]);
765 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
766 $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}"]);
769 list($hasAddressField, $addressParams) = CRM_Contribute_BAO_Contribution
::getPaymentProcessorReadyAddressParams($this->_params
, $this->_bltID
);
770 if ($hasAddressField) {
771 $this->_params
= array_merge($this->_params
, $addressParams);
774 $nameFields = array('first_name', 'middle_name', 'last_name');
775 foreach ($nameFields as $name) {
777 if (array_key_exists("billing_$name", $this->_params
)) {
778 $this->_params
[$name] = $this->_params
["billing_{$name}"];
779 $this->_params
['preserveDBName'] = TRUE;
786 * Handle Payment Processor switching for contribution and event registration forms.
788 * This function is shared between contribution & event forms & this is their common class.
790 * However, this should be seen as an in-progress refactor, the end goal being to also align the
791 * backoffice forms that action payments.
793 * This function overlaps assignPaymentProcessor, in a bad way.
795 protected function preProcessPaymentOptions() {
796 $this->_paymentProcessorID
= NULL;
797 if ($this->_paymentProcessors
) {
798 if (!empty($this->_submitValues
)) {
799 $this->_paymentProcessorID
= CRM_Utils_Array
::value('payment_processor_id', $this->_submitValues
);
800 $this->_paymentProcessor
= CRM_Utils_Array
::value($this->_paymentProcessorID
, $this->_paymentProcessors
);
801 $this->set('type', $this->_paymentProcessorID
);
802 $this->set('mode', $this->_mode
);
803 $this->set('paymentProcessor', $this->_paymentProcessor
);
805 // Set default payment processor
807 foreach ($this->_paymentProcessors
as $values) {
808 if (!empty($values['is_default']) ||
count($this->_paymentProcessors
) == 1) {
809 $this->_paymentProcessorID
= $values['id'];
814 if ($this->_paymentProcessorID
815 ||
(isset($this->_submitValues
['payment_processor_id']) && $this->_submitValues
['payment_processor_id'] == 0)
817 CRM_Core_Payment_ProcessorForm
::preProcess($this);
820 $this->_paymentProcessor
= array();
822 CRM_Financial_Form_Payment
::addCreditCardJs($this->_paymentProcessorID
);
824 $this->assign('paymentProcessorID', $this->_paymentProcessorID
);
825 // We save the fact that the profile 'billing' is required on the payment form.
826 // Currently pay-later is the only 'processor' that takes notice of this - but ideally
827 // 1) it would be possible to select the minimum_billing_profile_id for the contribution form
828 // 2) that profile_id would be set on the payment processor
829 // 3) the payment processor would return a billing form that combines these user-configured
830 // minimums with the payment processor minimums. This would lead to fields like 'postal_code'
831 // only being on the form if either the admin has configured it as wanted or the processor
833 $this->assign('billing_profile_id', (CRM_Utils_Array
::value('is_billing_required', $this->_values
) ?
'billing' : ''));
837 * Handle pre approval for processors.
839 * This fits with the flow where a pre-approval is done and then confirmed in the next stage when confirm is hit.
841 * This function is shared between contribution & event forms & this is their common class.
843 * However, this should be seen as an in-progress refactor, the end goal being to also align the
844 * backoffice forms that action payments.
846 * @param array $params
848 protected function handlePreApproval(&$params) {
850 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
851 $params['component'] = 'contribute';
852 $result = $payment->doPreApproval($params);
853 if (empty($result)) {
854 // This could happen, for example, when paypal looks at the button value & decides it is not paypal express.
858 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
859 CRM_Core_Error
::statusBounce(ts('Payment approval failed with message :') . $e->getMessage(), $payment->getCancelUrl($params['qfKey'], CRM_Utils_Array
::value('participant_id', $params)));
862 $this->set('pre_approval_parameters', $result['pre_approval_parameters']);
863 if (!empty($result['redirect_url'])) {
864 CRM_Utils_System
::redirect($result['redirect_url']);
869 * Setter function for options.
871 * @param mixed $options
873 public function setOptions($options) {
874 $this->_options
= $options;
878 * Render form and return contents.
882 public function toSmarty() {
883 $this->preProcessChainSelectFields();
884 $renderer = $this->getRenderer();
885 $this->accept($renderer);
886 $content = $renderer->toArray();
887 $content['formName'] = $this->getName();
889 $content['formClass'] = CRM_Utils_System
::getClassName($this);
894 * Getter function for renderer.
896 * If renderer is not set create one and initialize it.
900 public function &getRenderer() {
901 if (!isset($this->_renderer
)) {
902 $this->_renderer
= CRM_Core_Form_Renderer
::singleton();
904 return $this->_renderer
;
908 * Use the form name to create the tpl file name.
912 public function getTemplateFileName() {
913 $ext = CRM_Extension_System
::singleton()->getMapper();
914 if ($ext->isExtensionClass(CRM_Utils_System
::getClassName($this))) {
915 $filename = $ext->getTemplateName(CRM_Utils_System
::getClassName($this));
916 $tplname = $ext->getTemplatePath(CRM_Utils_System
::getClassName($this)) . DIRECTORY_SEPARATOR
. $filename;
920 CRM_Utils_System
::getClassName($this),
922 '_' => DIRECTORY_SEPARATOR
,
923 '\\' => DIRECTORY_SEPARATOR
,
931 * A wrapper for getTemplateFileName.
933 * This includes calling the hook to prevent us from having to copy & paste the logic of calling the hook.
935 public function getHookedTemplateFileName() {
936 $pageTemplateFile = $this->getTemplateFileName();
937 CRM_Utils_Hook
::alterTemplateFile(get_class($this), $this, 'page', $pageTemplateFile);
938 return $pageTemplateFile;
942 * Default extra tpl file basically just replaces .tpl with .extra.tpl.
944 * i.e. we do not override.
948 public function overrideExtraTemplateFileName() {
953 * Error reporting mechanism.
955 * @param string $message
959 * @param CRM_Core_DAO $dao
960 * A data access object on which we perform a rollback if non - empty.
962 public function error($message, $code = NULL, $dao = NULL) {
964 $dao->query('ROLLBACK');
967 $error = CRM_Core_Error
::singleton();
969 $error->push($code, $message);
973 * Store the variable with the value in the form scope.
975 * @param string $name
976 * Name of the variable.
977 * @param mixed $value
978 * Value of the variable.
980 public function set($name, $value) {
981 $this->controller
->set($name, $value);
985 * Get the variable from the form scope.
987 * @param string $name
988 * Name of the variable
992 public function get($name) {
993 return $this->controller
->get($name);
1001 public function getAction() {
1002 return $this->_action
;
1006 * Setter for action.
1008 * @param int $action
1009 * The mode we want to set the form.
1011 public function setAction($action) {
1012 $this->_action
= $action;
1016 * Assign value to name in template.
1018 * @param string $var
1020 * @param mixed $value
1021 * Value of variable.
1023 public function assign($var, $value = NULL) {
1024 self
::$_template->assign($var, $value);
1028 * Assign value to name in template by reference.
1030 * @param string $var
1032 * @param mixed $value
1033 * Value of variable.
1035 public function assign_by_ref($var, &$value) {
1036 self
::$_template->assign_by_ref($var, $value);
1040 * Appends values to template variables.
1042 * @param array|string $tpl_var the template variable name(s)
1043 * @param mixed $value
1044 * The value to append.
1045 * @param bool $merge
1047 public function append($tpl_var, $value = NULL, $merge = FALSE) {
1048 self
::$_template->append($tpl_var, $value, $merge);
1052 * Returns an array containing template variables.
1054 * @param string $name
1058 public function get_template_vars($name = NULL) {
1059 return self
::$_template->get_template_vars($name);
1063 * @param string $name
1066 * @param array $attributes
1067 * @param null $separator
1068 * @param bool $required
1070 * @return HTML_QuickForm_group
1072 public function &addRadio($name, $title, $values, $attributes = array(), $separator = NULL, $required = FALSE) {
1074 $attributes = $attributes ?
$attributes : array();
1075 $allowClear = !empty($attributes['allowClear']);
1076 unset($attributes['allowClear']);
1077 $attributes['id_suffix'] = $name;
1078 foreach ($values as $key => $var) {
1079 $options[] = $this->createElement('radio', NULL, NULL, $var, $key, $attributes);
1081 $group = $this->addGroup($options, $name, $title, $separator);
1083 $this->addRule($name, ts('%1 is a required field.', array(1 => $title)), 'required');
1086 $group->setAttribute('allowClear', TRUE);
1094 * @param bool $allowClear
1095 * @param null $required
1096 * @param array $attributes
1098 public function addYesNo($id, $title, $allowClear = FALSE, $required = NULL, $attributes = array()) {
1099 $attributes +
= array('id_suffix' => $id);
1101 $choice[] = $this->createElement('radio', NULL, '11', ts('Yes'), '1', $attributes);
1102 $choice[] = $this->createElement('radio', NULL, '11', ts('No'), '0', $attributes);
1104 $group = $this->addGroup($choice, $id, $title);
1106 $group->setAttribute('allowClear', TRUE);
1109 $this->addRule($id, ts('%1 is a required field.', array(1 => $title)), 'required');
1117 * @param null $other
1118 * @param null $attributes
1119 * @param null $required
1120 * @param null $javascriptMethod
1121 * @param string $separator
1122 * @param bool $flipValues
1124 public function addCheckBox(
1125 $id, $title, $values, $other = NULL,
1126 $attributes = NULL, $required = NULL,
1127 $javascriptMethod = NULL,
1128 $separator = '<br />', $flipValues = FALSE
1132 if ($javascriptMethod) {
1133 foreach ($values as $key => $var) {
1135 $options[] = $this->createElement('checkbox', $var, NULL, $key, $javascriptMethod);
1138 $options[] = $this->createElement('checkbox', $key, NULL, $var, $javascriptMethod);
1143 foreach ($values as $key => $var) {
1145 $options[] = $this->createElement('checkbox', $var, NULL, $key);
1148 $options[] = $this->createElement('checkbox', $key, NULL, $var);
1153 $this->addGroup($options, $id, $title, $separator);
1156 $this->addElement('text', $id . '_other', ts('Other'), $attributes[$id . '_other']);
1161 ts('%1 is a required field.', array(1 => $title)),
1167 public function resetValues() {
1168 $data = $this->controller
->container();
1169 $data['values'][$this->_name
] = array();
1173 * Simple shell that derived classes can call to add buttons to
1174 * the form with a customized title for the main Submit
1176 * @param string $title
1177 * Title of the main button.
1178 * @param string $nextType
1179 * Button type for the form after processing.
1180 * @param string $backType
1181 * @param bool|string $submitOnce If true, add javascript to next button submit which prevents it from being clicked more than once
1183 public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
1185 if ($backType != NULL) {
1187 'type' => $backType,
1188 'name' => ts('Previous'),
1191 if ($nextType != NULL) {
1192 $nextButton = array(
1193 'type' => $nextType,
1195 'isDefault' => TRUE,
1198 $nextButton['js'] = array('onclick' => "return submitOnce(this,'{$this->_name}','" . ts('Processing') . "');");
1200 $buttons[] = $nextButton;
1202 $this->addButtons($buttons);
1206 * @param string $name
1207 * @param string $from
1209 * @param string $label
1210 * @param string $dateFormat
1211 * @param bool $required
1212 * @param bool $displayTime
1214 public function addDateRange($name, $from = '_from', $to = '_to', $label = 'From:', $dateFormat = 'searchDate', $required = FALSE, $displayTime = FALSE) {
1216 $this->addDateTime($name . $from, $label, $required, array('formatType' => $dateFormat));
1217 $this->addDateTime($name . $to, ts('To:'), $required, array('formatType' => $dateFormat));
1220 $this->addDate($name . $from, $label, $required, array('formatType' => $dateFormat));
1221 $this->addDate($name . $to, ts('To:'), $required, array('formatType' => $dateFormat));
1226 * Based on form action, return a string representing the api action.
1227 * Used by addField method.
1231 private function getApiAction() {
1232 $action = $this->getAction();
1233 if ($action & (CRM_Core_Action
::UPDATE + CRM_Core_Action
::ADD
)) {
1236 if ($action & (CRM_Core_Action
::BROWSE + CRM_Core_Action
::BASIC + CRM_Core_Action
::ADVANCED + CRM_Core_Action
::PREVIEW
)) {
1239 // If you get this exception try adding more cases above.
1240 throw new Exception("Cannot determine api action for " . get_class($this) . '.' . 'CRM_Core_Action "' . CRM_Core_Action
::description($action) . '" not recognized.');
1244 * Classes extending CRM_Core_Form should implement this method.
1247 public function getDefaultEntity() {
1248 throw new Exception("Cannot determine default entity. " . get_class($this) . " should implement getDefaultEntity().");
1252 * Classes extending CRM_Core_Form should implement this method.
1254 * TODO: Merge with CRM_Core_DAO::buildOptionsContext($context) and add validation.
1257 public function getDefaultContext() {
1258 throw new Exception("Cannot determine default context. " . get_class($this) . " should implement getDefaultContext().");
1262 * Adds a select based on field metadata.
1263 * TODO: This could be even more generic and widget type (select in this case) could also be read from metadata
1264 * Perhaps a method like $form->bind($name) which would look up all metadata for named field
1266 * Field name to go on the form.
1267 * @param array $props
1268 * Mix of html attributes and special properties, namely.
1269 * - entity (api entity name, can usually be inferred automatically from the form class)
1270 * - field (field name - only needed if different from name used on the form)
1271 * - option_url - path to edit this option list - usually retrieved automatically - set to NULL to disable link
1272 * - placeholder - set to NULL to disable
1274 * - context - @see CRM_Core_DAO::buildOptionsContext
1275 * @param bool $required
1276 * @throws CRM_Core_Exception
1277 * @return HTML_QuickForm_Element
1279 public function addSelect($name, $props = array(), $required = FALSE) {
1280 if (!isset($props['entity'])) {
1281 $props['entity'] = $this->getDefaultEntity();
1283 if (!isset($props['field'])) {
1284 $props['field'] = strrpos($name, '[') ?
rtrim(substr($name, 1 +
strrpos($name, '[')), ']') : $name;
1286 if (!isset($props['context'])) {
1288 $props['context'] = $this->getDefaultContext();
1290 // This is not a required param, so we'll ignore if this doesn't exist.
1291 catch (Exception
$e) {}
1293 // Fetch options from the api unless passed explicitly
1294 if (isset($props['options'])) {
1295 $options = $props['options'];
1298 $info = civicrm_api3($props['entity'], 'getoptions', $props);
1299 $options = $info['values'];
1301 if (!array_key_exists('placeholder', $props)) {
1302 $props['placeholder'] = $required ?
ts('- select -') : CRM_Utils_Array
::value('context', $props) == 'search' ?
ts('- any -') : ts('- none -');
1304 // Handle custom field
1305 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
1306 list(, $id) = explode('_', $name);
1307 $label = isset($props['label']) ?
$props['label'] : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', 'label', $id);
1308 $gid = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', 'option_group_id', $id);
1309 if (CRM_Utils_Array
::value('context', $props) != 'search') {
1310 $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);
1315 $info = civicrm_api3($props['entity'], 'getfields');
1316 foreach ($info['values'] as $uniqueName => $fieldSpec) {
1318 $uniqueName === $props['field'] ||
1319 CRM_Utils_Array
::value('name', $fieldSpec) === $props['field'] ||
1320 in_array($props['field'], CRM_Utils_Array
::value('api.aliases', $fieldSpec, array()))
1325 $label = isset($props['label']) ?
$props['label'] : $fieldSpec['title'];
1326 if (CRM_Utils_Array
::value('context', $props) != 'search') {
1327 $props['data-option-edit-path'] = array_key_exists('option_url', $props) ?
$props['option_url'] : CRM_Core_PseudoConstant
::getOptionEditUrl($fieldSpec);
1330 $props['class'] = (isset($props['class']) ?
$props['class'] . ' ' : '') . "crm-select2";
1331 $props['data-api-entity'] = $props['entity'];
1332 $props['data-api-field'] = $props['field'];
1333 CRM_Utils_Array
::remove($props, 'label', 'entity', 'field', 'option_url', 'options', 'context');
1334 return $this->add('select', $name, $label, $options, $required, $props);
1338 * Adds a field based on metadata.
1341 * Field name to go on the form.
1342 * @param array $props
1343 * Mix of html attributes and special properties, namely.
1344 * - entity (api entity name, can usually be inferred automatically from the form class)
1345 * - name (field name - only needed if different from name used on the form)
1346 * - option_url - path to edit this option list - usually retrieved automatically - set to NULL to disable link
1347 * - placeholder - set to NULL to disable
1349 * - context - @see CRM_Core_DAO::buildOptionsContext
1350 * @param bool $required
1351 * @throws \CiviCRM_API3_Exception
1352 * @throws \Exception
1353 * @return HTML_QuickForm_Element
1355 public function addField($name, $props = array(), $required = FALSE) {
1357 if (empty($props['context'])) {
1358 $props['context'] = $this->getDefaultContext();
1360 $context = $props['context'];
1362 if (empty($props['entity'])) {
1363 $props['entity'] = $this->getDefaultEntity();
1366 if (empty($props['name'])) {
1367 $props['name'] = strrpos($name, '[') ?
rtrim(substr($name, 1 +
strrpos($name, '[')), ']') : $name;
1370 if (empty($props['action'])) {
1371 $props['action'] = $this->getApiAction();
1374 // Handle custom fields
1375 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
1376 $fieldId = (int) substr($name, 7);
1377 return CRM_Core_BAO_CustomField
::addQuickFormElement($this, $name, $fieldId, $required, $context == 'search', CRM_Utils_Array
::value('label', $props));
1380 // Core field - get metadata.
1381 $fieldSpec = civicrm_api3($props['entity'], 'getfield', $props);
1382 $fieldSpec = $fieldSpec['values'];
1383 $label = CRM_Utils_Array
::value('label', $props, isset($fieldSpec['title']) ?
$fieldSpec['title'] : NULL);
1385 $widget = isset($props['type']) ?
$props['type'] : $fieldSpec['html']['type'];
1386 if ($widget == 'TextArea' && $context == 'search') {
1390 $isSelect = (in_array($widget, array(
1398 // Fetch options from the api unless passed explicitly.
1399 if (isset($props['options'])) {
1400 $options = $props['options'];
1403 $options = isset($fieldSpec['options']) ?
$fieldSpec['options'] : NULL;
1405 if ($context == 'search') {
1407 $props['multiple'] = CRM_Utils_Array
::value('multiple', $props, TRUE);
1410 // Add data for popup link.
1411 if ((!empty($props['option_url']) ||
!array_key_exists('option_url', $props)) && ($context != 'search' && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM'))) {
1412 $props['data-option-edit-path'] = !empty($props['option_url']) ?
$props['option_url'] : CRM_Core_PseudoConstant
::getOptionEditUrl($fieldSpec);
1413 $props['data-api-entity'] = $props['entity'];
1414 $props['data-api-field'] = $props['name'];
1417 $props +
= CRM_Utils_Array
::value('html', $fieldSpec, array());
1418 CRM_Utils_Array
::remove($props, 'entity', 'name', 'context', 'label', 'action', 'type', 'option_url', 'options');
1420 // TODO: refactor switch statement, to separate methods.
1426 //TODO: Autodetect ranges
1427 $props['size'] = isset($props['size']) ?
$props['size'] : 60;
1428 return $this->add(strtolower($widget), $name, $label, $props, $required);
1431 return $this->add('hidden', $name, NULL, $props, $required);
1434 //Set default columns and rows for textarea.
1435 $props['rows'] = isset($props['rows']) ?
$props['rows'] : 4;
1436 $props['cols'] = isset($props['cols']) ?
$props['cols'] : 60;
1437 return $this->add('textarea', $name, $label, $props, $required);
1440 //TODO: add range support
1441 //TODO: Add date formats
1442 //TODO: Add javascript template for dates.
1443 return $this->addDate($name, $label, $required, $props);
1446 $separator = isset($props['separator']) ?
$props['separator'] : NULL;
1447 unset($props['separator']);
1448 if (!isset($props['allowClear'])) {
1449 $props['allowClear'] = !$required;
1451 return $this->addRadio($name, $label, $options, $props, $separator, $required);
1455 'required' => $required,
1457 'multiple' => $context == 'search',
1459 return $this->addChainSelect($name, $props);
1462 $props['class'] = CRM_Utils_Array
::value('class', $props, 'big') . ' crm-select2';
1463 if (!array_key_exists('placeholder', $props)) {
1464 $props['placeholder'] = $required ?
ts('- select -') : ($context == 'search' ?
ts('- any -') : ts('- none -'));
1466 // TODO: Add and/or option for fields that store multiple values
1467 return $this->add('select', $name, $label, $options, $required, $props);
1469 case 'CheckBoxGroup':
1470 return $this->addCheckBox($name, $label, array_flip($options), $required, $props);
1473 return $this->addRadio($name, $label, $options, $props, NULL, $required);
1476 $text = isset($props['text']) ?
$props['text'] : NULL;
1477 unset($props['text']);
1478 return $this->addElement('checkbox', $name, $label, $text, $props);
1480 //add support for 'Advcheckbox' field
1482 $text = isset($props['text']) ?
$props['text'] : NULL;
1483 unset($props['text']);
1484 return $this->addElement('advcheckbox', $name, $label, $text, $props);
1487 // We should not build upload file in search mode.
1488 if ($context == 'search') {
1491 $file = $this->add('file', $name, $label, $props, $required);
1492 $this->addUploadElement($name);
1495 case 'RichTextEditor':
1496 return $this->add('wysiwyg', $name, $label, $props, $required);
1499 return $this->addEntityRef($name, $label, $props, $required);
1501 // Check datatypes of fields
1505 //case read only fields
1507 throw new Exception("Unsupported html-element " . $widget);
1512 * Add a widget for selecting/editing/creating/copying a profile form
1514 * @param string $name
1515 * HTML form-element name.
1516 * @param string $label
1518 * @param string $allowCoreTypes
1519 * Only present a UFGroup if its group_type includes a subset of $allowCoreTypes; e.g. 'Individual', 'Activity'.
1520 * @param string $allowSubTypes
1521 * Only present a UFGroup if its group_type is compatible with $allowSubypes.
1522 * @param array $entities
1523 * @param bool $default
1525 * @param string $usedFor
1527 public function addProfileSelector($name, $label, $allowCoreTypes, $allowSubTypes, $entities, $default = FALSE, $usedFor = NULL) {
1529 // FIXME: Instead of adhoc serialization, use a single json_encode()
1530 CRM_UF_Page_ProfileEditor
::registerProfileScripts();
1531 CRM_UF_Page_ProfileEditor
::registerSchemas(CRM_Utils_Array
::collect('entity_type', $entities));
1532 $this->add('text', $name, $label, array(
1533 'class' => 'crm-profile-selector',
1534 // Note: client treats ';;' as equivalent to \0, and ';;' works better in HTML
1535 'data-group-type' => CRM_Core_BAO_UFGroup
::encodeGroupType($allowCoreTypes, $allowSubTypes, ';;'),
1536 'data-entities' => json_encode($entities),
1538 'data-default' => $default,
1539 'data-usedfor' => json_encode($usedFor),
1546 public function getRootTitle() {
1553 public function getCompleteTitle() {
1554 return $this->getRootTitle() . $this->getTitle();
1558 * @return CRM_Core_Smarty
1560 public static function &getTemplate() {
1561 return self
::$_template;
1565 * @param $elementName
1567 public function addUploadElement($elementName) {
1568 $uploadNames = $this->get('uploadNames');
1569 if (!$uploadNames) {
1570 $uploadNames = array();
1572 if (is_array($elementName)) {
1573 foreach ($elementName as $name) {
1574 if (!in_array($name, $uploadNames)) {
1575 $uploadNames[] = $name;
1580 if (!in_array($elementName, $uploadNames)) {
1581 $uploadNames[] = $elementName;
1584 $this->set('uploadNames', $uploadNames);
1586 $config = CRM_Core_Config
::singleton();
1587 if (!empty($uploadNames)) {
1588 $this->controller
->addUploadAction($config->customFileUploadDir
, $uploadNames);
1597 public function getVar($name) {
1598 return isset($this->$name) ?
$this->$name : NULL;
1605 public function setVar($name, $value) {
1606 $this->$name = $value;
1613 * Use $this->add('datepicker', ...) instead.
1615 * @param string $name
1616 * Name of the element.
1617 * @param string $label
1618 * Label of the element.
1619 * @param bool $required
1621 * @param array $attributes
1624 public function addDate($name, $label, $required = FALSE, $attributes = NULL) {
1625 if (!empty($attributes['formatType'])) {
1626 // get actual format
1627 $params = array('name' => $attributes['formatType']);
1630 // cache date information
1632 $key = "dateFormat_" . str_replace(' ', '_', $attributes['formatType']);
1633 if (empty($dateFormat[$key])) {
1634 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
1635 $dateFormat[$key] = $values;
1638 $values = $dateFormat[$key];
1641 if ($values['date_format']) {
1642 $attributes['format'] = $values['date_format'];
1645 if (!empty($values['time_format'])) {
1646 $attributes['timeFormat'] = $values['time_format'];
1648 $attributes['startOffset'] = $values['start'];
1649 $attributes['endOffset'] = $values['end'];
1652 $config = CRM_Core_Config
::singleton();
1653 if (empty($attributes['format'])) {
1654 $attributes['format'] = $config->dateInputFormat
;
1657 if (!isset($attributes['startOffset'])) {
1658 $attributes['startOffset'] = 10;
1661 if (!isset($attributes['endOffset'])) {
1662 $attributes['endOffset'] = 10;
1665 $this->add('text', $name, $label, $attributes);
1667 if (!empty($attributes['addTime']) ||
!empty($attributes['timeFormat'])) {
1669 if (!isset($attributes['timeFormat'])) {
1670 $timeFormat = $config->timeInputFormat
;
1673 $timeFormat = $attributes['timeFormat'];
1676 // 1 - 12 hours and 2 - 24 hours, but for jquery widget it is 0 and 1 respectively
1678 $show24Hours = TRUE;
1679 if ($timeFormat == 1) {
1680 $show24Hours = FALSE;
1683 //CRM-6664 -we are having time element name
1684 //in either flat string or an array format.
1685 $elementName = $name . '_time';
1686 if (substr($name, -1) == ']') {
1687 $elementName = substr($name, 0, strlen($name) - 1) . '_time]';
1690 $this->add('text', $elementName, ts('Time'), array('timeFormat' => $show24Hours));
1695 $this->addRule($name, ts('Please select %1', array(1 => $label)), 'required');
1696 if (!empty($attributes['addTime']) && !empty($attributes['addTimeRequired'])) {
1697 $this->addRule($elementName, ts('Please enter a time.'), 'required');
1703 * Function that will add date and time.
1706 * Use $this->add('datepicker', ...) instead.
1708 * @param string $name
1709 * @param string $label
1710 * @param bool $required
1711 * @param null $attributes
1713 public function addDateTime($name, $label, $required = FALSE, $attributes = NULL) {
1714 $addTime = array('addTime' => TRUE);
1715 if (is_array($attributes)) {
1716 $attributes = array_merge($attributes, $addTime);
1719 $attributes = $addTime;
1722 $this->addDate($name, $label, $required, $attributes);
1726 * Add a currency and money element to the form.
1728 * @param string $name
1729 * @param string $label
1730 * @param bool $required
1731 * @param null $attributes
1732 * @param bool $addCurrency
1733 * @param string $currencyName
1734 * @param null $defaultCurrency
1735 * @param bool $freezeCurrency
1737 * @return \HTML_QuickForm_Element
1739 public function addMoney(
1744 $addCurrency = TRUE,
1745 $currencyName = 'currency',
1746 $defaultCurrency = NULL,
1747 $freezeCurrency = FALSE
1749 $element = $this->add('text', $name, $label, $attributes, $required);
1750 $this->addRule($name, ts('Please enter a valid amount.'), 'money');
1753 $ele = $this->addCurrency($currencyName, NULL, TRUE, $defaultCurrency, $freezeCurrency);
1760 * Add currency element to the form.
1762 * @param string $name
1763 * @param null $label
1764 * @param bool $required
1765 * @param string $defaultCurrency
1766 * @param bool $freezeCurrency
1768 public function addCurrency(
1772 $defaultCurrency = NULL,
1773 $freezeCurrency = FALSE
1775 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
1776 $options = array('class' => 'crm-select2 eight');
1778 $currencies = array('' => '') +
$currencies;
1779 $options['placeholder'] = ts('- none -');
1781 $ele = $this->add('select', $name, $label, $currencies, $required, $options);
1782 if ($freezeCurrency) {
1785 if (!$defaultCurrency) {
1786 $config = CRM_Core_Config
::singleton();
1787 $defaultCurrency = $config->defaultCurrency
;
1789 $this->setDefaults(array($name => $defaultCurrency));
1793 * Create a single or multiple entity ref field.
1794 * @param string $name
1795 * @param string $label
1796 * @param array $props
1797 * Mix of html and widget properties, including:.
1798 * - select - params to give to select2 widget
1799 * - entity - defaults to contact
1800 * - create - can the user create a new entity on-the-fly?
1801 * Set to TRUE if entity is contact and you want the default profiles,
1802 * or pass in your own set of links. @see CRM_Core_BAO_UFGroup::getCreateLinks for format
1803 * note that permissions are checked automatically
1804 * - api - array of settings for the getlist api wrapper
1805 * note that it accepts a 'params' setting which will be passed to the underlying api
1806 * - placeholder - string
1808 * - class, etc. - other html properties
1809 * @param bool $required
1811 * @return HTML_QuickForm_Element
1813 public function addEntityRef($name, $label = '', $props = array(), $required = FALSE) {
1814 require_once "api/api.php";
1815 $config = CRM_Core_Config
::singleton();
1816 // Default properties
1817 $props['api'] = CRM_Utils_Array
::value('api', $props, array());
1818 $props['entity'] = _civicrm_api_get_entity_name_from_camel(CRM_Utils_Array
::value('entity', $props, 'contact'));
1819 $props['class'] = ltrim(CRM_Utils_Array
::value('class', $props, '') . ' crm-form-entityref');
1821 if ($props['entity'] == 'contact' && isset($props['create']) && !(CRM_Core_Permission
::check('edit all contacts') || CRM_Core_Permission
::check('add contacts'))) {
1822 unset($props['create']);
1825 $props['placeholder'] = CRM_Utils_Array
::value('placeholder', $props, $required ?
ts('- select %1 -', array(1 => ts(str_replace('_', ' ', $props['entity'])))) : ts('- none -'));
1827 $defaults = array();
1828 if (!empty($props['multiple'])) {
1829 $defaults['multiple'] = TRUE;
1831 $props['select'] = CRM_Utils_Array
::value('select', $props, array()) +
$defaults;
1833 $this->formatReferenceFieldAttributes($props);
1834 return $this->add('text', $name, $label, $props, $required);
1840 private function formatReferenceFieldAttributes(&$props) {
1841 $props['data-select-params'] = json_encode($props['select']);
1842 $props['data-api-params'] = $props['api'] ?
json_encode($props['api']) : NULL;
1843 $props['data-api-entity'] = $props['entity'];
1844 if (!empty($props['create'])) {
1845 $props['data-create-links'] = json_encode($props['create']);
1847 CRM_Utils_Array
::remove($props, 'multiple', 'select', 'api', 'entity', 'create');
1851 * Convert all date fields within the params to mysql date ready for the
1852 * BAO layer. In this case fields are checked against the $_datefields defined for the form
1853 * and if time is defined it is incorporated
1855 * @param array $params
1856 * Input params from the form.
1858 * @todo it would probably be better to work on $this->_params than a passed array
1859 * @todo standardise the format which dates are passed to the BAO layer in & remove date
1862 public function convertDateFieldsToMySQL(&$params) {
1863 foreach ($this->_dateFields
as $fieldName => $specs) {
1864 if (!empty($params[$fieldName])) {
1865 $params[$fieldName] = CRM_Utils_Date
::isoToMysql(
1866 CRM_Utils_Date
::processDate(
1867 $params[$fieldName],
1868 CRM_Utils_Array
::value("{$fieldName}_time", $params), TRUE)
1872 if (isset($specs['default'])) {
1873 $params[$fieldName] = date('YmdHis', strtotime($specs['default']));
1880 * @param $elementName
1882 public function removeFileRequiredRules($elementName) {
1883 $this->_required
= array_diff($this->_required
, array($elementName));
1884 if (isset($this->_rules
[$elementName])) {
1885 foreach ($this->_rules
[$elementName] as $index => $ruleInfo) {
1886 if ($ruleInfo['type'] == 'uploadedfile') {
1887 unset($this->_rules
[$elementName][$index]);
1890 if (empty($this->_rules
[$elementName])) {
1891 unset($this->_rules
[$elementName]);
1897 * Function that can be defined in Form to override or.
1898 * perform specific action on cancel action
1900 public function cancelAction() {
1904 * Helper function to verify that required fields have been filled.
1906 * Typically called within the scope of a FormRule function
1908 * @param array $fields
1909 * @param array $values
1910 * @param array $errors
1912 public static function validateMandatoryFields($fields, $values, &$errors) {
1913 foreach ($fields as $name => $fld) {
1914 if (!empty($fld['is_required']) && CRM_Utils_System
::isNull(CRM_Utils_Array
::value($name, $values))) {
1915 $errors[$name] = ts('%1 is a required field.', array(1 => $fld['title']));
1921 * Get contact if for a form object. Prioritise
1922 * - cid in URL if 0 (on behalf on someoneelse)
1923 * (@todo consider setting a variable if onbehalf for clarity of downstream 'if's
1924 * - logged in user id if it matches the one in the cid in the URL
1925 * - contact id validated from a checksum from a checksum
1926 * - cid from the url if the caller has ACL permission to view
1927 * - fallback is logged in user (or ? NULL if no logged in user) (@todo wouldn't 0 be more intuitive?)
1931 protected function setContactID() {
1932 $tempID = CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
1933 if (isset($this->_params
) && !empty($this->_params
['select_contact_id'])) {
1934 $tempID = $this->_params
['select_contact_id'];
1936 if (isset($this->_params
, $this->_params
[0]) && !empty($this->_params
[0]['select_contact_id'])) {
1937 // event form stores as an indexed array, contribution form not so much...
1938 $tempID = $this->_params
[0]['select_contact_id'];
1941 // force to ignore the authenticated user
1942 if ($tempID === '0' ||
$tempID === 0) {
1943 // we set the cid on the form so that this will be retained for the Confirm page
1944 // in the multi-page form & prevent us returning the $userID when this is called
1946 // we don't really need to set it when $tempID is set because the params have that stored
1947 $this->set('cid', 0);
1948 CRM_Core_Resources
::singleton()->addVars('coreForm', array('contact_id' => (int) $tempID));
1949 return (int) $tempID;
1952 $userID = $this->getLoggedInUserContactID();
1954 if (!is_null($tempID) && $tempID === $userID) {
1955 CRM_Core_Resources
::singleton()->addVars('coreForm', array('contact_id' => (int) $tempID));
1956 return (int) $userID;
1959 //check if this is a checksum authentication
1960 $userChecksum = CRM_Utils_Request
::retrieve('cs', 'String', $this);
1961 if ($userChecksum) {
1962 //check for anonymous user.
1963 $validUser = CRM_Contact_BAO_Contact_Utils
::validChecksum($tempID, $userChecksum);
1965 CRM_Core_Resources
::singleton()->addVars('coreForm', array('contact_id' => (int) $tempID));
1966 CRM_Core_Resources
::singleton()->addVars('coreForm', array('checksum' => (int) $tempID));
1970 // check if user has permission, CRM-12062
1971 elseif ($tempID && CRM_Contact_BAO_Contact_Permission
::allow($tempID)) {
1972 CRM_Core_Resources
::singleton()->addVars('coreForm', array('contact_id' => (int) $tempID));
1975 if (is_numeric($userID)) {
1976 CRM_Core_Resources
::singleton()->addVars('coreForm', array('contact_id' => (int) $userID));
1978 return is_numeric($userID) ?
$userID : NULL;
1982 * Get the contact id that the form is being submitted for.
1986 public function getContactID() {
1987 return $this->setContactID();
1991 * Get the contact id of the logged in user.
1993 public function getLoggedInUserContactID() {
1994 // check if the user is logged in and has a contact ID
1995 $session = CRM_Core_Session
::singleton();
1996 return $session->get('userID');
2000 * Add autoselector field -if user has permission to view contacts
2001 * If adding this to a form you also need to add to the tpl e.g
2003 * {if !empty($selectable)}
2004 * <div class="crm-summary-row">
2005 * <div class="crm-label">{$form.select_contact.label}</div>
2006 * <div class="crm-content">
2007 * {$form.select_contact.html}
2012 * @param array $profiles
2013 * Ids of profiles that are on the form (to be autofilled).
2014 * @param array $autoCompleteField
2018 * - url (for ajax lookup)
2020 * @todo add data attributes so we can deal with multiple instances on a form
2022 public function addAutoSelector($profiles = array(), $autoCompleteField = array()) {
2023 $autoCompleteField = array_merge(array(
2024 'id_field' => 'select_contact_id',
2025 'placeholder' => ts('Select someone else ...'),
2026 'show_hide' => TRUE,
2027 'api' => array('params' => array('contact_type' => 'Individual')),
2028 ), $autoCompleteField);
2030 if ($this->canUseAjaxContactLookups()) {
2031 $this->assign('selectable', $autoCompleteField['id_field']);
2032 $this->addEntityRef($autoCompleteField['id_field'], NULL, array(
2033 'placeholder' => $autoCompleteField['placeholder'],
2034 'api' => $autoCompleteField['api'],
2037 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/AlternateContactSelector.js', 1, 'html-header')
2039 'form' => array('autocompletes' => $autoCompleteField),
2040 'ids' => array('profile' => $profiles),
2047 public function canUseAjaxContactLookups() {
2048 if (0 < (civicrm_api3('contact', 'getcount', array('check_permissions' => 1))) &&
2049 CRM_Core_Permission
::check(array(array('access AJAX API', 'access CiviCRM')))
2056 * Add the options appropriate to cid = zero - ie. autocomplete
2058 * @todo there is considerable code duplication between the contribution forms & event forms. It is apparent
2059 * that small pieces of duplication are not being refactored into separate functions because their only shared parent
2060 * is this form. Inserting a class FrontEndForm.php between the contribution & event & this class would allow functions like this
2061 * and a dozen other small ones to be refactored into a shared parent with the reduction of much code duplication
2063 * @param $onlinePaymentProcessorEnabled
2065 public function addCIDZeroOptions($onlinePaymentProcessorEnabled) {
2066 $this->assign('nocid', TRUE);
2067 $profiles = array();
2068 if ($this->_values
['custom_pre_id']) {
2069 $profiles[] = $this->_values
['custom_pre_id'];
2071 if ($this->_values
['custom_post_id']) {
2072 $profiles = array_merge($profiles, (array) $this->_values
['custom_post_id']);
2074 if ($onlinePaymentProcessorEnabled) {
2075 $profiles[] = 'billing';
2077 if (!empty($this->_values
)) {
2078 $this->addAutoSelector($profiles);
2083 * Set default values on form for given contact (or no contact defaults)
2085 * @param mixed $profile_id
2086 * (can be id, or profile name).
2087 * @param int $contactID
2091 public function getProfileDefaults($profile_id = 'Billing', $contactID = NULL) {
2093 $defaults = civicrm_api3('profile', 'getsingle', array(
2094 'profile_id' => (array) $profile_id,
2095 'contact_id' => $contactID,
2099 catch (Exception
$e) {
2100 // the try catch block gives us silent failure -not 100% sure this is a good idea
2101 // as silent failures are often worse than noisy ones
2107 * Sets form attribute.
2110 public function preventAjaxSubmit() {
2111 $this->setAttribute('data-no-ajax-submit', 'true');
2115 * Sets form attribute.
2118 public function allowAjaxSubmit() {
2119 $this->removeAttribute('data-no-ajax-submit');
2123 * Sets page title based on entity and action.
2124 * @param string $entityLabel
2126 public function setPageTitle($entityLabel) {
2127 switch ($this->_action
) {
2128 case CRM_Core_Action
::ADD
:
2129 CRM_Utils_System
::setTitle(ts('New %1', array(1 => $entityLabel)));
2132 case CRM_Core_Action
::UPDATE
:
2133 CRM_Utils_System
::setTitle(ts('Edit %1', array(1 => $entityLabel)));
2136 case CRM_Core_Action
::VIEW
:
2137 case CRM_Core_Action
::PREVIEW
:
2138 CRM_Utils_System
::setTitle(ts('View %1', array(1 => $entityLabel)));
2141 case CRM_Core_Action
::DELETE
:
2142 CRM_Utils_System
::setTitle(ts('Delete %1', array(1 => $entityLabel)));
2148 * Create a chain-select target field. All settings are optional; the defaults usually work.
2150 * @param string $elementName
2151 * @param array $settings
2153 * @return HTML_QuickForm_Element
2155 public function addChainSelect($elementName, $settings = array()) {
2156 $props = $settings +
= array(
2157 'control_field' => str_replace(array('state_province', 'StateProvince', 'county', 'County'), array(
2163 'data-callback' => strpos($elementName, 'rovince') ?
'civicrm/ajax/jqState' : 'civicrm/ajax/jqCounty',
2164 'label' => strpos($elementName, 'rovince') ?
ts('State/Province') : ts('County'),
2165 'data-empty-prompt' => strpos($elementName, 'rovince') ?
ts('Choose country first') : ts('Choose state first'),
2166 'data-none-prompt' => ts('- N/A -'),
2167 'multiple' => FALSE,
2168 'required' => FALSE,
2169 'placeholder' => empty($settings['required']) ?
ts('- none -') : ts('- select -'),
2171 CRM_Utils_Array
::remove($props, 'label', 'required', 'control_field', 'context');
2172 $props['class'] = (empty($props['class']) ?
'' : "{$props['class']} ") . 'crm-select2';
2173 $props['data-select-prompt'] = $props['placeholder'];
2174 $props['data-name'] = $elementName;
2176 $this->_chainSelectFields
[$settings['control_field']] = $elementName;
2178 // Passing NULL instead of an array of options
2179 // CRM-15225 - normally QF will reject any selected values that are not part of the field's options, but due to a
2180 // quirk in our patched version of HTML_QuickForm_select, this doesn't happen if the options are NULL
2181 // which seems a bit dirty but it allows our dynamically-popuplated select element to function as expected.
2182 return $this->add('select', $elementName, $settings['label'], NULL, $settings['required'], $props);
2186 * Add actions menu to results form.
2188 * @param array $tasks
2190 public function addTaskMenu($tasks) {
2191 if (is_array($tasks) && !empty($tasks)) {
2192 // Set constants means this will always load with an empty value, not reloading any submitted value.
2193 // This is appropriate as it is a pseudofield.
2194 $this->setConstants(array('task' => ''));
2195 $this->assign('taskMetaData', $tasks);
2196 $select = $this->add('select', 'task', NULL, array('' => ts('Actions')), FALSE, array(
2197 'class' => 'crm-select2 crm-action-menu fa-check-circle-o huge crm-search-result-actions')
2199 foreach ($tasks as $key => $task) {
2200 $attributes = array();
2201 if (isset($task['data'])) {
2202 foreach ($task['data'] as $dataKey => $dataValue) {
2203 $attributes['data-' . $dataKey] = $dataValue;
2206 $select->addOption($task['title'], $key, $attributes);
2208 if (empty($this->_actionButtonName
)) {
2209 $this->_actionButtonName
= $this->getButtonName('next', 'action');
2211 $this->assign('actionButtonName', $this->_actionButtonName
);
2212 $this->add('submit', $this->_actionButtonName
, ts('Go'), array('class' => 'hiddenElement crm-search-go-button'));
2214 // Radio to choose "All items" or "Selected items only"
2215 $selectedRowsRadio = $this->addElement('radio', 'radio_ts', NULL, '', 'ts_sel', array('checked' => 'checked'));
2216 $allRowsRadio = $this->addElement('radio', 'radio_ts', NULL, '', 'ts_all');
2217 $this->assign('ts_sel_id', $selectedRowsRadio->_attributes
['id']);
2218 $this->assign('ts_all_id', $allRowsRadio->_attributes
['id']);
2220 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header');
2225 * Set options and attributes for chain select fields based on the controlling field's value
2227 private function preProcessChainSelectFields() {
2228 foreach ($this->_chainSelectFields
as $control => $target) {
2229 // The 'target' might get missing if extensions do removeElement() in a form hook.
2230 if ($this->elementExists($target)) {
2231 $targetField = $this->getElement($target);
2232 $targetType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ?
'county' : 'stateProvince';
2234 // If the control field is on the form, setup chain-select and dynamically populate options
2235 if ($this->elementExists($control)) {
2236 $controlField = $this->getElement($control);
2237 $controlType = $targetType == 'county' ?
'stateProvince' : 'country';
2239 $targetField->setAttribute('class', $targetField->getAttribute('class') . ' crm-chain-select-target');
2241 $css = (string) $controlField->getAttribute('class');
2242 $controlField->updateAttributes(array(
2243 'class' => ($css ?
"$css " : 'crm-select2 ') . 'crm-chain-select-control',
2244 'data-target' => $target,
2246 $controlValue = $controlField->getValue();
2247 if ($controlValue) {
2248 $options = CRM_Core_BAO_Location
::getChainSelectValues($controlValue, $controlType, TRUE);
2250 $targetField->setAttribute('placeholder', $targetField->getAttribute('data-none-prompt'));
2254 $targetField->setAttribute('placeholder', $targetField->getAttribute('data-empty-prompt'));
2255 $targetField->setAttribute('disabled', 'disabled');
2258 // Control field not present - fall back to loading default options
2260 $options = CRM_Core_PseudoConstant
::$targetType();
2262 if (!$targetField->getAttribute('multiple')) {
2263 $options = array('' => $targetField->getAttribute('placeholder')) +
$options;
2264 $targetField->removeAttribute('placeholder');
2266 $targetField->_options
= array();
2267 $targetField->loadArray($options);
2273 * Validate country / state / county match and suppress unwanted "required" errors
2275 private function validateChainSelectFields() {
2276 foreach ($this->_chainSelectFields
as $control => $target) {
2277 if ($this->elementExists($control) && $this->elementExists($target)) {
2278 $controlValue = (array) $this->getElementValue($control);
2279 $targetField = $this->getElement($target);
2280 $controlType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ?
'stateProvince' : 'country';
2281 $targetValue = array_filter((array) $targetField->getValue());
2282 if ($targetValue ||
$this->getElementError($target)) {
2283 $options = CRM_Core_BAO_Location
::getChainSelectValues($controlValue, $controlType, TRUE);
2285 if (!array_intersect($targetValue, array_keys($options))) {
2286 $this->setElementError($target, $controlType == 'country' ?
ts('State/Province does not match the selected Country') : ts('County does not match the selected State/Province'));
2288 } // Suppress "required" error for field if it has no options
2289 elseif (!$options) {
2290 $this->setElementError($target, NULL);
2298 * Assign billing name to the template.
2300 * @param array $params
2301 * Form input params, default to $this->_params.
2303 public function assignBillingName($params = array()) {
2305 if (empty($params)) {
2306 $params = $this->_params
;
2308 if (!empty($params['billing_first_name'])) {
2309 $name = $params['billing_first_name'];
2312 if (!empty($params['billing_middle_name'])) {
2313 $name .= " {$params['billing_middle_name']}";
2316 if (!empty($params['billing_last_name'])) {
2317 $name .= " {$params['billing_last_name']}";
2319 $name = trim($name);
2320 $this->assign('billingName', $name);