3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
39 require_once 'HTML/QuickForm/Page.php';
44 class CRM_Core_Form
extends HTML_QuickForm_Page
{
47 * The state object that this form belongs to
53 * The name of this form
59 * The title of this form
62 protected $_title = NULL;
65 * The default values for the form.
69 public $_defaults = array();
72 * The options passed into this form
75 protected $_options = NULL;
78 * The mode of operation for this form
84 * Available payment processors.
86 * As part of trying to consolidate various payment pages we store processors here & have functions
87 * at this level to manage them.
90 * An array of payment processor details with objects loaded in the 'object' field.
92 protected $_paymentProcessors;
95 * Available payment processors (IDS).
97 * As part of trying to consolidate various payment pages we store processors here & have functions
98 * at this level to manage them.
101 * An array of the IDS available on this form.
103 public $_paymentProcessorIDs;
106 * The renderer used for this form
110 protected $_renderer;
113 * An array to hold a list of datefields on the form
114 * so that they can be converted to ISO in a consistent manner
118 * e.g on a form declare $_dateFields = array(
119 * 'receive_date' => array('default' => 'now'),
121 * then in postProcess call $this->convertDateFieldsToMySQL($formValues)
122 * to have the time field re-incorporated into the field & 'now' set if
123 * no value has been passed in
125 protected $_dateFields = array();
128 * Cache the smarty template for efficiency reasons
130 * @var CRM_Core_Smarty
132 static protected $_template;
135 * Indicate if this form should warn users of unsaved changes
137 protected $unsavedChangesWarn;
140 * What to return to the client if in ajax mode (snippet=json)
144 public $ajaxResponse = array();
147 * Url path used to reach this page
151 public $urlPath = array();
154 * @var CRM_Core_Controller
159 * Constants for attributes for various form elements
160 * attempt to standardize on the number of variations that we
161 * use of the below form elements
165 const ATTR_SPACING
= ' ';
168 * All checkboxes are defined with a common prefix. This allows us to
169 * have the same javascript to check / clear all the checkboxes etc
170 * If u have multiple groups of checkboxes, you will need to give them different
171 * ids to avoid potential name collision
175 const CB_PREFIX
= 'mark_x_', CB_PREFIY
= 'mark_y_', CB_PREFIZ
= 'mark_z_', CB_PREFIX_LEN
= 7;
178 * @internal to keep track of chain-select fields
181 private $_chainSelectFields = array();
184 * Constructor for the basic form page.
186 * We should not use QuickForm directly. This class provides a lot
187 * of default convenient functions, rules and buttons
189 * @param object $state
190 * State associated with this form.
191 * @param \const|\enum|int $action The mode the form is operating in (None/Create/View/Update/Delete)
192 * @param string $method
193 * The type of http method used (GET/POST).
194 * @param string $name
195 * The name of the form if different from class name.
197 * @return \CRM_Core_Form
199 public function __construct(
201 $action = CRM_Core_Action
::NONE
,
207 $this->_name
= $name;
210 // CRM-15153 - FIXME this name translates to a DOM id and is not always unique!
211 $this->_name
= CRM_Utils_String
::getClassName(CRM_Utils_System
::getClassName($this));
214 $this->HTML_QuickForm_Page($this->_name
, $method);
216 $this->_state
=& $state;
218 $this->_state
->setName($this->_name
);
220 $this->_action
= (int) $action;
222 $this->registerRules();
224 // let the constructor initialize this, should happen only once
225 if (!isset(self
::$_template)) {
226 self
::$_template = CRM_Core_Smarty
::singleton();
228 // Workaround for CRM-15153 - give each form a reasonably unique css class
229 $this->addClass(CRM_Utils_System
::getClassName($this));
231 $this->assign('snippet', CRM_Utils_Array
::value('snippet', $_GET));
234 public static function generateID() {
238 * Add one or more css classes to the form
239 * @param string $className
241 public function addClass($className) {
242 $classes = $this->getAttribute('class');
243 $this->setAttribute('class', ($classes ?
"$classes " : '') . $className);
247 * Register all the standard rules that most forms potentially use.
251 public function registerRules() {
252 static $rules = array(
280 foreach ($rules as $rule) {
281 $this->registerRule($rule, 'callback', $rule, 'CRM_Utils_Rule');
286 * Simple easy to use wrapper around addElement. Deal with
287 * simple validation rules
289 * @param string $type
290 * @param string $name
291 * @param string $label
292 * @param string|array $attributes (options for select elements)
293 * @param bool $required
294 * @param array $extra
295 * (attributes for select elements).
297 * @return HTML_QuickForm_Element could be an error object
299 public function &add(
300 $type, $name, $label = '',
301 $attributes = '', $required = FALSE, $extra = NULL
303 if ($type == 'wysiwyg') {
304 $attributes = ($attributes ?
$attributes : array()) +
array('class' => '');
305 $attributes['class'] .= ' crm-form-wysiwyg';
308 if ($type == 'select' && is_array($extra)) {
309 // Normalize this property
310 if (!empty($extra['multiple'])) {
311 $extra['multiple'] = 'multiple';
314 unset($extra['multiple']);
316 // Add placeholder option for select
317 if (isset($extra['placeholder'])) {
318 if ($extra['placeholder'] === TRUE) {
319 $extra['placeholder'] = $required ?
ts('- select -') : ts('- none -');
321 if (($extra['placeholder'] ||
$extra['placeholder'] === '') && empty($extra['multiple']) && is_array($attributes) && !isset($attributes[''])) {
322 $attributes = array('' => $extra['placeholder']) +
$attributes;
326 $element = $this->addElement($type, $name, $label, $attributes, $extra);
327 if (HTML_QuickForm
::isError($element)) {
328 CRM_Core_Error
::fatal(HTML_QuickForm
::errorMessage($element));
332 if ($type == 'file') {
333 $error = $this->addRule($name, ts('%1 is a required field.', array(1 => $label)), 'uploadedfile');
336 $error = $this->addRule($name, ts('%1 is a required field.', array(1 => $label)), 'required');
338 if (HTML_QuickForm
::isError($error)) {
339 CRM_Core_Error
::fatal(HTML_QuickForm
::errorMessage($element));
347 * called before buildForm. Any pre-processing that
348 * needs to be done for buildForm should be done here
350 * This is a virtual function and should be redefined if needed
355 public function preProcess() {
359 * called after the form is validated. Any
360 * processing of form state etc should be done in this function.
361 * Typically all processing associated with a form should be done
362 * here and relevant state should be stored in the session
364 * This is a virtual function and should be redefined if needed
369 public function postProcess() {
373 * just a wrapper, so that we can call all the hook functions
374 * @param bool $allowAjax
375 * FIXME: This feels kind of hackish, ideally we would take the json-related code from this function.
376 * and bury it deeper down in the controller
378 public function mainProcess($allowAjax = TRUE) {
379 $this->postProcess();
380 $this->postProcessHook();
382 // Respond with JSON if in AJAX context (also support legacy value '6')
383 if ($allowAjax && !empty($_REQUEST['snippet']) && in_array($_REQUEST['snippet'], array(
384 CRM_Core_Smarty
::PRINT_JSON
,
388 $this->ajaxResponse
['buttonName'] = str_replace('_qf_' . $this->getAttribute('id') . '_', '', $this->controller
->getButtonName());
389 $this->ajaxResponse
['action'] = $this->_action
;
390 if (isset($this->_id
) ||
isset($this->id
)) {
391 $this->ajaxResponse
['id'] = isset($this->id
) ?
$this->id
: $this->_id
;
393 CRM_Core_Page_AJAX
::returnJsonResponse($this->ajaxResponse
);
398 * The postProcess hook is typically called by the framework.
399 * However in a few cases, the form exits or redirects early in which
400 * case it needs to call this function so other modules can do the needful
401 * Calling this function directly should be avoided if possible. In general a
402 * better way is to do setUserContext so the framework does the redirect
404 public function postProcessHook() {
405 CRM_Utils_Hook
::postProcess(get_class($this), $this);
409 * This virtual function is used to build the form. It replaces the
410 * buildForm associated with QuickForm_Page. This allows us to put
411 * preProcess in front of the actual form building routine
416 public function buildQuickForm() {
420 * This virtual function is used to set the default values of
421 * various form elements
426 * reference to the array of default values
428 public function setDefaultValues() {
433 * This is a virtual function that adds group and global rules to
434 * the form. Keeping it distinct from the form to keep code small
435 * and localized in the form building code
440 public function addRules() {
444 * Performs the server side validation.
447 * true if no error found
448 * @throws HTML_QuickForm_Error
450 public function validate() {
451 $error = parent
::validate();
453 $this->validateChainSelectFields();
455 $hookErrors = array();
457 CRM_Utils_Hook
::validateForm(
459 $this->_submitValues
,
465 if (!empty($hookErrors)) {
466 $this->_errors +
= $hookErrors;
469 return (0 == count($this->_errors
));
473 * Core function that builds the form. We redefine this function
474 * here and expect all CRM forms to build their form in the function
477 public function buildForm() {
478 $this->_formBuilt
= TRUE;
482 CRM_Utils_Hook
::preProcess(get_class($this), $this);
484 $this->assign('translatePermission', CRM_Core_Permission
::check('translate CiviCRM'));
487 $this->controller
->_key
&&
488 $this->controller
->_generateQFKey
490 $this->addElement('hidden', 'qfKey', $this->controller
->_key
);
491 $this->assign('qfKey', $this->controller
->_key
);
495 // _generateQFKey suppresses the qfKey generation on form snippets that
496 // are part of other forms, hence we use that to avoid adding entryURL
497 if ($this->controller
->_generateQFKey
&& $this->controller
->_entryURL
) {
498 $this->addElement('hidden', 'entryURL', $this->controller
->_entryURL
);
501 $this->buildQuickForm();
503 $defaults = $this->setDefaultValues();
504 unset($defaults['qfKey']);
506 if (!empty($defaults)) {
507 $this->setDefaults($defaults);
510 // call the form hook
511 // also call the hook function so any modules can set their own custom defaults
512 // the user can do both the form and set default values with this hook
513 CRM_Utils_Hook
::buildForm(get_class($this), $this);
517 //Set html data-attribute to enable warning user of unsaved changes
518 if ($this->unsavedChangesWarn
=== TRUE
519 ||
(!isset($this->unsavedChangesWarn
)
520 && ($this->_action
& CRM_Core_Action
::ADD ||
$this->_action
& CRM_Core_Action
::UPDATE
)
523 $this->setAttribute('data-warn-changes', 'true');
528 * Add default Next / Back buttons
530 * @param array $params
531 * Array of associative arrays in the order in which the buttons should be
532 * displayed. The associate array has 3 fields: 'type', 'name' and 'isDefault'
533 * The base form class will define a bunch of static arrays for commonly used
538 public function addButtons($params) {
539 $prevnext = $spacing = array();
540 foreach ($params as $button) {
541 $attrs = array('class' => 'crm-form-submit') +
(array) CRM_Utils_Array
::value('js', $button);
543 if (!empty($button['class'])) {
544 $attrs['class'] .= ' ' . $button['class'];
547 if (!empty($button['isDefault'])) {
548 $attrs['class'] .= ' default';
551 if (in_array($button['type'], array('upload', 'next', 'submit', 'done', 'process', 'refresh'))) {
552 $attrs['class'] .= ' validate';
553 $defaultIcon = 'check';
556 $attrs['class'] .= ' cancel';
557 $defaultIcon = $button['type'] == 'back' ?
'triangle-1-w' : 'close';
560 if ($button['type'] === 'reset') {
561 $prevnext[] = $this->createElement($button['type'], 'reset', $button['name'], $attrs);
564 if (!empty($button['subName'])) {
565 if ($button['subName'] == 'new') {
566 $defaultIcon = 'plus';
568 if ($button['subName'] == 'done') {
569 $defaultIcon = 'circle-check';
571 if ($button['subName'] == 'next') {
572 $defaultIcon = 'circle-triangle-e';
576 if (in_array($button['type'], array('next', 'upload', 'done')) && $button['name'] === ts('Save')) {
577 $attrs['accesskey'] = 'S';
579 $icon = CRM_Utils_Array
::value('icon', $button, $defaultIcon);
581 $attrs['crm-icon'] = $icon;
583 $buttonName = $this->getButtonName($button['type'], CRM_Utils_Array
::value('subName', $button));
584 $prevnext[] = $this->createElement('submit', $buttonName, $button['name'], $attrs);
586 if (!empty($button['isDefault'])) {
587 $this->setDefaultAction($button['type']);
590 // if button type is upload, set the enctype
591 if ($button['type'] == 'upload') {
592 $this->updateAttributes(array('enctype' => 'multipart/form-data'));
593 $this->setMaxFileSize();
596 // hack - addGroup uses an array to express variable spacing, read from the last element
597 $spacing[] = CRM_Utils_Array
::value('spacing', $button, self
::ATTR_SPACING
);
599 $this->addGroup($prevnext, 'buttons', '', $spacing, FALSE);
603 * Getter function for Name.
607 public function getName() {
612 * Getter function for State.
616 public function &getState() {
617 return $this->_state
;
621 * Getter function for StateType.
625 public function getStateType() {
626 return $this->_state
->getType();
630 * Getter function for title. Should be over-ridden by derived class
634 public function getTitle() {
635 return $this->_title ?
$this->_title
: ts('ERROR: Title is not Set');
639 * Setter function for title.
641 * @param string $title
642 * The title of the form.
644 public function setTitle($title) {
645 $this->_title
= $title;
649 * Assign billing type id to bltID.
651 * @throws CRM_Core_Exception
653 public function assignBillingType() {
654 $this->_bltID
= CRM_Core_BAO_Location
::getBillingLocationId();
655 $this->set('bltID', $this->_bltID
);
656 $this->assign('bltID', $this->_bltID
);
660 * This if a front end form function for setting the payment processor.
662 * It would be good to sync it with the back-end function on abstractEditPayment & use one everywhere.
664 * @throws \CRM_Core_Exception
666 protected function assignPaymentProcessor() {
667 $this->_paymentProcessors
= CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors(
668 array(ucfirst($this->_mode
) . 'Mode'),
669 $this->_paymentProcessorIDs
672 if (!empty($this->_paymentProcessors
)) {
673 foreach ($this->_paymentProcessors
as $paymentProcessorID => $paymentProcessorDetail) {
674 if (empty($this->_paymentProcessor
) && $paymentProcessorDetail['is_default'] == 1 ||
(count($this->_paymentProcessors
) == 1)
676 $this->_paymentProcessor
= $paymentProcessorDetail;
677 $this->assign('paymentProcessor', $this->_paymentProcessor
);
678 // Setting this is a bit of a legacy overhang.
679 $this->_paymentObject
= $paymentProcessorDetail['object'];
682 // It's not clear why we set this on the form.
683 $this->set('paymentProcessors', $this->_paymentProcessors
);
686 throw new CRM_Core_Exception(ts('A payment processor configured for this page might be disabled (contact the site administrator for assistance).'));
691 * Handle Payment Processor switching for contribution and event registration forms.
693 * This function is shared between contribution & event forms & this is their common class.
695 * However, this should be seen as an in-progress refactor, the end goal being to also align the
696 * backoffice forms that action payments.
698 * This function overlaps assignPaymentProcessor, in a bad way.
700 protected function preProcessPaymentOptions() {
701 $this->_paymentProcessorID
= NULL;
702 if ($this->_paymentProcessors
) {
703 if (!empty($this->_submitValues
)) {
704 $this->_paymentProcessorID
= CRM_Utils_Array
::value('payment_processor_id', $this->_submitValues
);
705 $this->_paymentProcessor
= CRM_Utils_Array
::value($this->_paymentProcessorID
, $this->_paymentProcessors
);
706 $this->set('type', $this->_paymentProcessorID
);
707 $this->set('mode', $this->_mode
);
708 $this->set('paymentProcessor', $this->_paymentProcessor
);
710 // Set default payment processor
712 foreach ($this->_paymentProcessors
as $values) {
713 if (!empty($values['is_default']) ||
count($this->_paymentProcessors
) == 1) {
714 $this->_paymentProcessorID
= $values['id'];
719 if ($this->_paymentProcessorID
) {
720 CRM_Core_Payment_ProcessorForm
::preProcess($this);
723 $this->_paymentProcessor
= array();
725 CRM_Financial_Form_Payment
::addCreditCardJs();
727 $this->assign('paymentProcessorID', $this->_paymentProcessorID
);
731 * Setter function for options.
733 * @param mixed $options
737 public function setOptions($options) {
738 $this->_options
= $options;
742 * Getter function for link.
746 public function getLink() {
747 $config = CRM_Core_Config
::singleton();
748 return CRM_Utils_System
::url($_GET[$config->userFrameworkURLVar
],
749 '_qf_' . $this->_name
. '_display=true'
754 * Boolean function to determine if this is a one form page.
758 public function isSimpleForm() {
759 return $this->_state
->getType() & (CRM_Core_State
::START | CRM_Core_State
::FINISH
);
763 * Getter function for Form Action.
767 public function getFormAction() {
768 return $this->_attributes
['action'];
772 * Setter function for Form Action.
774 * @param string $action
778 public function setFormAction($action) {
779 $this->_attributes
['action'] = $action;
783 * Render form and return contents.
787 public function toSmarty() {
788 $this->preProcessChainSelectFields();
789 $renderer = $this->getRenderer();
790 $this->accept($renderer);
791 $content = $renderer->toArray();
792 $content['formName'] = $this->getName();
794 $content['formClass'] = CRM_Utils_System
::getClassName($this);
799 * Getter function for renderer. If renderer is not set
800 * create one and initialize it
804 public function &getRenderer() {
805 if (!isset($this->_renderer
)) {
806 $this->_renderer
= CRM_Core_Form_Renderer
::singleton();
808 return $this->_renderer
;
812 * Use the form name to create the tpl file name.
816 public function getTemplateFileName() {
817 $ext = CRM_Extension_System
::singleton()->getMapper();
818 if ($ext->isExtensionClass(CRM_Utils_System
::getClassName($this))) {
819 $filename = $ext->getTemplateName(CRM_Utils_System
::getClassName($this));
820 $tplname = $ext->getTemplatePath(CRM_Utils_System
::getClassName($this)) . DIRECTORY_SEPARATOR
. $filename;
824 CRM_Utils_System
::getClassName($this),
826 '_' => DIRECTORY_SEPARATOR
,
827 '\\' => DIRECTORY_SEPARATOR
,
835 * A wrapper for getTemplateFileName that includes calling the hook to
836 * prevent us from having to copy & paste the logic of calling the hook
838 public function getHookedTemplateFileName() {
839 $pageTemplateFile = $this->getTemplateFileName();
840 CRM_Utils_Hook
::alterTemplateFile(get_class($this), $this, 'page', $pageTemplateFile);
841 return $pageTemplateFile;
845 * Default extra tpl file basically just replaces .tpl with .extra.tpl
846 * i.e. we dont override
850 public function overrideExtraTemplateFileName() {
855 * Error reporting mechanism.
857 * @param string $message
861 * @param CRM_Core_DAO $dao
862 * A data access object on which we perform a rollback if non - empty.
866 public function error($message, $code = NULL, $dao = NULL) {
868 $dao->query('ROLLBACK');
871 $error = CRM_Core_Error
::singleton();
873 $error->push($code, $message);
877 * Store the variable with the value in the form scope.
879 * @param string $name
880 * Name of the variable.
881 * @param mixed $value
882 * Value of the variable.
886 public function set($name, $value) {
887 $this->controller
->set($name, $value);
891 * Get the variable from the form scope.
893 * @param string $name
894 * Name of the variable
898 public function get($name) {
899 return $this->controller
->get($name);
907 public function getAction() {
908 return $this->_action
;
915 * The mode we want to set the form.
919 public function setAction($action) {
920 $this->_action
= $action;
924 * Assign value to name in template.
928 * @param mixed $value
933 public function assign($var, $value = NULL) {
934 self
::$_template->assign($var, $value);
938 * Assign value to name in template by reference.
942 * @param mixed $value
947 public function assign_by_ref($var, &$value) {
948 self
::$_template->assign_by_ref($var, $value);
952 * Appends values to template variables.
954 * @param array|string $tpl_var the template variable name(s)
955 * @param mixed $value
956 * The value to append.
959 public function append($tpl_var, $value = NULL, $merge = FALSE) {
960 self
::$_template->append($tpl_var, $value, $merge);
964 * Returns an array containing template variables.
966 * @param string $name
970 public function get_template_vars($name = NULL) {
971 return self
::$_template->get_template_vars($name);
975 * @param string $name
978 * @param array $attributes
979 * @param null $separator
980 * @param bool $required
982 * @return HTML_QuickForm_group
984 public function &addRadio($name, $title, $values, $attributes = array(), $separator = NULL, $required = FALSE) {
986 $attributes = $attributes ?
$attributes : array();
987 $allowClear = !empty($attributes['allowClear']);
988 unset($attributes['allowClear']);
989 $attributes['id_suffix'] = $name;
990 foreach ($values as $key => $var) {
991 $options[] = $this->createElement('radio', NULL, NULL, $var, $key, $attributes);
993 $group = $this->addGroup($options, $name, $title, $separator);
995 $this->addRule($name, ts('%1 is a required field.', array(1 => $title)), 'required');
998 $group->setAttribute('allowClear', TRUE);
1006 * @param bool $allowClear
1007 * @param null $required
1008 * @param array $attributes
1010 public function addYesNo($id, $title, $allowClear = FALSE, $required = NULL, $attributes = array()) {
1011 $attributes +
= array('id_suffix' => $id);
1013 $choice[] = $this->createElement('radio', NULL, '11', ts('Yes'), '1', $attributes);
1014 $choice[] = $this->createElement('radio', NULL, '11', ts('No'), '0', $attributes);
1016 $group = $this->addGroup($choice, $id, $title);
1018 $group->setAttribute('allowClear', TRUE);
1021 $this->addRule($id, ts('%1 is a required field.', array(1 => $title)), 'required');
1029 * @param null $other
1030 * @param null $attributes
1031 * @param null $required
1032 * @param null $javascriptMethod
1033 * @param string $separator
1034 * @param bool $flipValues
1036 public function addCheckBox(
1037 $id, $title, $values, $other = NULL,
1038 $attributes = NULL, $required = NULL,
1039 $javascriptMethod = NULL,
1040 $separator = '<br />', $flipValues = FALSE
1044 if ($javascriptMethod) {
1045 foreach ($values as $key => $var) {
1047 $options[] = $this->createElement('checkbox', $var, NULL, $key, $javascriptMethod);
1050 $options[] = $this->createElement('checkbox', $key, NULL, $var, $javascriptMethod);
1055 foreach ($values as $key => $var) {
1057 $options[] = $this->createElement('checkbox', $var, NULL, $key);
1060 $options[] = $this->createElement('checkbox', $key, NULL, $var);
1065 $this->addGroup($options, $id, $title, $separator);
1068 $this->addElement('text', $id . '_other', ts('Other'), $attributes[$id . '_other']);
1073 ts('%1 is a required field.', array(1 => $title)),
1079 public function resetValues() {
1080 $data = $this->controller
->container();
1081 $data['values'][$this->_name
] = array();
1085 * Simple shell that derived classes can call to add buttons to
1086 * the form with a customized title for the main Submit
1088 * @param string $title
1089 * Title of the main button.
1090 * @param string $nextType
1091 * Button type for the form after processing.
1092 * @param string $backType
1093 * @param bool|string $submitOnce If true, add javascript to next button submit which prevents it from being clicked more than once
1097 public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
1099 if ($backType != NULL) {
1101 'type' => $backType,
1102 'name' => ts('Previous'),
1105 if ($nextType != NULL) {
1106 $nextButton = array(
1107 'type' => $nextType,
1109 'isDefault' => TRUE,
1112 $nextButton['js'] = array('onclick' => "return submitOnce(this,'{$this->_name}','" . ts('Processing') . "');");
1114 $buttons[] = $nextButton;
1116 $this->addButtons($buttons);
1120 * @param string $name
1121 * @param string $from
1123 * @param string $label
1124 * @param string $dateFormat
1125 * @param bool $required
1126 * @param bool $displayTime
1128 public function addDateRange($name, $from = '_from', $to = '_to', $label = 'From:', $dateFormat = 'searchDate', $required = FALSE, $displayTime = FALSE) {
1130 $this->addDateTime($name . $from, $label, $required, array('formatType' => $dateFormat));
1131 $this->addDateTime($name . $to, ts('To:'), $required, array('formatType' => $dateFormat));
1134 $this->addDate($name . $from, $label, $required, array('formatType' => $dateFormat));
1135 $this->addDate($name . $to, ts('To:'), $required, array('formatType' => $dateFormat));
1140 * Based on form action, return a string representing the api action.
1141 * Used by addField method.
1145 private function getApiAction() {
1146 $action = $this->getAction();
1147 if ($action & (CRM_Core_Action
::UPDATE + CRM_Core_Action
::ADD
)) {
1150 if ($action & (CRM_Core_Action
::BROWSE
)) {
1153 // If you get this exception try adding more cases above.
1154 throw new Exception("Cannot determine api action for " . __CLASS__
);
1158 * Classes extending CRM_Core_Form should implement this method.
1161 public function getDefaultEntity() {
1162 throw new Exception("Cannot determine default entity. The form class should implement getDefaultEntity().");
1166 * Classes extending CRM_Core_Form should implement this method.
1168 * TODO: Merge with CRM_Core_DAO::buildOptionsContext($context) and add validation.
1171 public function getDefaultContext() {
1172 throw new Exception("Cannot determine default context. The form class should implement getDefaultContext().");
1176 * Adds a select based on field metadata.
1177 * TODO: This could be even more generic and widget type (select in this case) could also be read from metadata
1178 * Perhaps a method like $form->bind($name) which would look up all metadata for named field
1180 * Field name to go on the form.
1181 * @param array $props
1182 * Mix of html attributes and special properties, namely.
1183 * - entity (api entity name, can usually be inferred automatically from the form class)
1184 * - field (field name - only needed if different from name used on the form)
1185 * - option_url - path to edit this option list - usually retrieved automatically - set to NULL to disable link
1186 * - placeholder - set to NULL to disable
1188 * - context - @see CRM_Core_DAO::buildOptionsContext
1189 * @param bool $required
1190 * @throws CRM_Core_Exception
1191 * @return HTML_QuickForm_Element
1193 public function addSelect($name, $props = array(), $required = FALSE) {
1194 if (!isset($props['entity'])) {
1195 $props['entity'] = $this->getDefaultEntity();
1197 if (!isset($props['field'])) {
1198 $props['field'] = strrpos($name, '[') ?
rtrim(substr($name, 1 +
strrpos($name, '[')), ']') : $name;
1200 // Fetch options from the api unless passed explicitly
1201 if (isset($props['options'])) {
1202 $options = $props['options'];
1205 $info = civicrm_api3($props['entity'], 'getoptions', $props +
array('check_permissions' => 1));
1206 $options = $info['values'];
1208 if (!array_key_exists('placeholder', $props)) {
1209 $props['placeholder'] = $required ?
ts('- select -') : CRM_Utils_Array
::value('context', $props) == 'search' ?
ts('- any -') : ts('- none -');
1211 // Handle custom field
1212 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
1213 list(, $id) = explode('_', $name);
1214 $label = isset($props['label']) ?
$props['label'] : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', 'label', $id);
1215 $gid = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', 'option_group_id', $id);
1216 if (CRM_Utils_Array
::value('context', $props) != 'search') {
1217 $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);
1222 $info = civicrm_api3($props['entity'], 'getfields');
1223 foreach ($info['values'] as $uniqueName => $fieldSpec) {
1225 $uniqueName === $props['field'] ||
1226 CRM_Utils_Array
::value('name', $fieldSpec) === $props['field'] ||
1227 in_array($props['field'], CRM_Utils_Array
::value('api.aliases', $fieldSpec, array()))
1232 $label = isset($props['label']) ?
$props['label'] : $fieldSpec['title'];
1233 if (CRM_Utils_Array
::value('context', $props) != 'search') {
1234 $props['data-option-edit-path'] = array_key_exists('option_url', $props) ?
$props['option_url'] : $props['data-option-edit-path'] = CRM_Core_PseudoConstant
::getOptionEditUrl($fieldSpec);
1237 $props['class'] = (isset($props['class']) ?
$props['class'] . ' ' : '') . "crm-select2";
1238 $props['data-api-entity'] = $props['entity'];
1239 $props['data-api-field'] = $props['field'];
1240 CRM_Utils_Array
::remove($props, 'label', 'entity', 'field', 'option_url', 'options', 'context');
1241 return $this->add('select', $name, $label, $options, $required, $props);
1245 * Adds a field based on metadata.
1248 * Field name to go on the form.
1249 * @param array $props
1250 * Mix of html attributes and special properties, namely.
1251 * - entity (api entity name, can usually be inferred automatically from the form class)
1252 * - name (field name - only needed if different from name used on the form)
1253 * - option_url - path to edit this option list - usually retrieved automatically - set to NULL to disable link
1254 * - placeholder - set to NULL to disable
1256 * - context - @see CRM_Core_DAO::buildOptionsContext
1257 * @param bool $required
1258 * @throws \CiviCRM_API3_Exception
1259 * @throws \Exception
1260 * @return HTML_QuickForm_Element
1262 public function addField($name, $props = array(), $required = FALSE) {
1263 // TODO: Handle custom field
1264 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
1265 throw new Exception("Custom fields are not supported by the addField method. ");
1268 if (!isset($props['context'])) {
1269 $props['context'] = $this->getDefaultContext();
1272 if (!isset($props['entity'])) {
1273 $props['entity'] = $this->getDefaultEntity();
1276 if (!isset($props['name'])) {
1277 $props['name'] = strrpos($name, '[') ?
rtrim(substr($name, 1 +
strrpos($name, '[')), ']') : $name;
1280 if (!isset($props['action'])) {
1281 $props['action'] = $this->getApiAction();
1283 // Get field metadata.
1284 $fieldSpec = civicrm_api3($props['entity'], 'getfield', $props);
1285 $fieldSpec = $fieldSpec['values'];
1286 $label = CRM_Utils_Array
::value('label', $props, isset($fieldSpec['title']) ?
$fieldSpec['title'] : NULL);
1288 $widget = isset($props['type']) ?
$props['type'] : $fieldSpec['html']['type'];
1289 if ($widget == 'TextArea' && $props['context'] == 'search') {
1293 $isSelect = (in_array($widget, array(
1296 'Select State/Province',
1297 'Multi-Select State/Province',
1299 'Multi-Select Country',
1307 // Fetch options from the api unless passed explicitly.
1308 if (isset($props['options'])) {
1309 $options = $props['options'];
1310 // Else this get passed to the form->add method.
1311 unset($props['options']);
1314 $options = isset($fieldSpec['options']) ?
$fieldSpec['options'] : NULL;
1316 //@TODO AdvMulti-Select is deprecated, drop support.
1317 if ($props['context'] == 'search' ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
1320 // Set default options-url value.
1321 if ((!isset($props['options-url']))) {
1322 $props['options-url'] = TRUE;
1325 // Add data for popup link.
1326 if ((isset($props['options-url']) && $props['options-url']) && ($props['context'] != 'search' && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM'))) {
1327 $props['data-option-edit-path'] = array_key_exists('option_url', $props) ?
$props['option_url'] : $props['data-option-edit-path'] = CRM_Core_PseudoConstant
::getOptionEditUrl($fieldSpec);
1328 $props['data-api-entity'] = $props['entity'];
1329 $props['data-api-field'] = $props['name'];
1330 if (isset($props['options-url'])) {
1331 unset($props['options-url']);
1335 //Use select2 library for following widgets.
1336 $isSelect2 = (in_array($widget, array(
1339 'Select State/Province',
1340 'Multi-Select State/Province',
1342 'Multi-Select Country',
1345 $props['class'] = (isset($props['class']) ?
$props['class'] . ' ' : '') . "crm-select2";
1346 if ($props['context'] == 'search' ||
strpos($widget, 'Multi') !== FALSE) {
1347 $props['class'] .= ' huge';
1348 $props['multiple'] = 'multiple';
1350 // The placeholder is only used for select-elements.
1351 if (!array_key_exists('placeholder', $props)) {
1352 $props['placeholder'] = $required ?
ts('- select -') : $props['context'] == 'search' ?
ts('- any -') : ts('- none -');
1355 $props +
= CRM_Utils_Array
::value('html', $fieldSpec, array());
1356 CRM_Utils_Array
::remove($props, 'entity', 'name', 'context', 'label', 'action', 'type');
1357 // TODO: refactor switch statement, to separate methods.
1361 //TODO: Autodetect ranges
1362 $props['size'] = isset($props['size']) ?
$props['size'] : 60;
1363 return $this->add('text', $name, $label, $props, $required);
1366 return $this->add('hidden', $name, NULL, $props, $required);
1369 //Set default columns and rows for textarea.
1370 $props['rows'] = isset($props['rows']) ?
$props['rows'] : 4;
1371 $props['cols'] = isset($props['cols']) ?
$props['cols'] : 60;
1372 return $this->addElement('textarea', $name, $label, $props, $required);
1375 //TODO: add range support
1376 //TODO: Add date formats
1377 //TODO: Add javascript template for dates.
1378 return $this->addDate($name, $label, $required, $props);
1381 $separator = isset($props['separator']) ?
$props['separator'] : NULL;
1382 unset($props['separator']);
1383 if (!isset($props['allowClear'])) {
1384 $props['allowClear'] = !$required;
1386 return $this->addRadio($name, $label, $options, $props, $separator, $required);
1389 if (empty($props['multiple'])) {
1390 $options = array('' => $props['placeholder']) +
$options;
1392 // TODO: Add and/or option for fields that store multiple values
1393 return $this->add('select', $name, $label, $options, $required, $props);
1395 case 'CheckBoxGroup':
1396 return $this->addCheckBox($name, $label, array_flip($options), $required, $props);
1399 return $this->addRadio($name, $label, $options, $props, NULL, $required);
1401 //case 'AdvMulti-Select':
1403 $text = isset($props['text']) ?
$props['text'] : NULL;
1404 unset($props['text']);
1405 return $this->addElement('checkbox', $name, $label, $text, $props);
1408 // We should not build upload file in search mode.
1409 if (isset($props['context']) && $props['context'] == 'search') {
1412 $file = $this->add('file', $name, $label, $props, $required);
1413 $this->addUploadElement($name);
1416 //case 'RichTextEditor':
1417 //TODO: Add javascript template for wysiwyg.
1418 case 'Autocomplete-Select':
1420 return $this->addEntityRef($name, $label, $props, $required);
1422 // Check datatypes of fields
1427 //case read only fields
1429 throw new Exception("Unsupported html-element " . $widget);
1434 * Add a widget for selecting/editing/creating/copying a profile form
1436 * @param string $name
1437 * HTML form-element name.
1438 * @param string $label
1440 * @param string $allowCoreTypes
1441 * Only present a UFGroup if its group_type includes a subset of $allowCoreTypes; e.g. 'Individual', 'Activity'.
1442 * @param string $allowSubTypes
1443 * Only present a UFGroup if its group_type is compatible with $allowSubypes.
1444 * @param array $entities
1445 * @param bool $default
1448 public function addProfileSelector($name, $label, $allowCoreTypes, $allowSubTypes, $entities, $default = FALSE, $usedFor = NULL) {
1450 // FIXME: Instead of adhoc serialization, use a single json_encode()
1451 CRM_UF_Page_ProfileEditor
::registerProfileScripts();
1452 CRM_UF_Page_ProfileEditor
::registerSchemas(CRM_Utils_Array
::collect('entity_type', $entities));
1453 $this->add('text', $name, $label, array(
1454 'class' => 'crm-profile-selector',
1455 // Note: client treats ';;' as equivalent to \0, and ';;' works better in HTML
1456 'data-group-type' => CRM_Core_BAO_UFGroup
::encodeGroupType($allowCoreTypes, $allowSubTypes, ';;'),
1457 'data-entities' => json_encode($entities),
1459 'data-default' => $default,
1460 'data-usedfor' => json_encode($usedFor),
1467 * @param null $required
1468 * @param null $extra
1470 public function addCountry($id, $title, $required = NULL, $extra = NULL) {
1471 $this->addElement('select', $id, $title,
1473 '' => ts('- select -'),
1474 ) + CRM_Core_PseudoConstant
::country(), $extra
1477 $this->addRule($id, ts('Please select %1', array(1 => $title)), 'required');
1482 * @param string $name
1485 * @param $attributes
1486 * @param null $required
1487 * @param null $javascriptMethod
1489 public function addSelectOther($name, $label, $options, $attributes, $required = NULL, $javascriptMethod = NULL) {
1491 $this->addElement('select', $name . '_id', $label, $options, $javascriptMethod);
1494 $this->addRule($name . '_id', ts('Please select %1', array(1 => $label)), 'required');
1501 public function getRootTitle() {
1508 public function getCompleteTitle() {
1509 return $this->getRootTitle() . $this->getTitle();
1513 * @return CRM_Core_Smarty
1515 public static function &getTemplate() {
1516 return self
::$_template;
1520 * @param $elementName
1522 public function addUploadElement($elementName) {
1523 $uploadNames = $this->get('uploadNames');
1524 if (!$uploadNames) {
1525 $uploadNames = array();
1527 if (is_array($elementName)) {
1528 foreach ($elementName as $name) {
1529 if (!in_array($name, $uploadNames)) {
1530 $uploadNames[] = $name;
1535 if (!in_array($elementName, $uploadNames)) {
1536 $uploadNames[] = $elementName;
1539 $this->set('uploadNames', $uploadNames);
1541 $config = CRM_Core_Config
::singleton();
1542 if (!empty($uploadNames)) {
1543 $this->controller
->addUploadAction($config->customFileUploadDir
, $uploadNames);
1550 public function buttonType() {
1551 $uploadNames = $this->get('uploadNames');
1552 $buttonType = (is_array($uploadNames) && !empty($uploadNames)) ?
'upload' : 'next';
1553 $this->assign('buttonType', $buttonType);
1562 public function getVar($name) {
1563 return isset($this->$name) ?
$this->$name : NULL;
1570 public function setVar($name, $value) {
1571 $this->$name = $value;
1578 * // if you need time
1579 * $attributes = array(
1580 * 'addTime' => true,
1581 * 'formatType' => 'relative' or 'birth' etc check advanced date settings
1585 * @param string $name
1586 * Name of the element.
1587 * @param string $label
1588 * Label of the element.
1589 * @param bool $required
1591 * @param array $attributes
1594 public function addDate($name, $label, $required = FALSE, $attributes = NULL) {
1595 if (!empty($attributes['formatType'])) {
1596 // get actual format
1597 $params = array('name' => $attributes['formatType']);
1600 // cache date information
1602 $key = "dateFormat_" . str_replace(' ', '_', $attributes['formatType']);
1603 if (empty($dateFormat[$key])) {
1604 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
1605 $dateFormat[$key] = $values;
1608 $values = $dateFormat[$key];
1611 if ($values['date_format']) {
1612 $attributes['format'] = $values['date_format'];
1615 if (!empty($values['time_format'])) {
1616 $attributes['timeFormat'] = $values['time_format'];
1618 $attributes['startOffset'] = $values['start'];
1619 $attributes['endOffset'] = $values['end'];
1622 $config = CRM_Core_Config
::singleton();
1623 if (empty($attributes['format'])) {
1624 $attributes['format'] = $config->dateInputFormat
;
1627 if (!isset($attributes['startOffset'])) {
1628 $attributes['startOffset'] = 10;
1631 if (!isset($attributes['endOffset'])) {
1632 $attributes['endOffset'] = 10;
1635 $this->add('text', $name, $label, $attributes);
1637 if (!empty($attributes['addTime']) ||
!empty($attributes['timeFormat'])) {
1639 if (!isset($attributes['timeFormat'])) {
1640 $timeFormat = $config->timeInputFormat
;
1643 $timeFormat = $attributes['timeFormat'];
1646 // 1 - 12 hours and 2 - 24 hours, but for jquery widget it is 0 and 1 respectively
1648 $show24Hours = TRUE;
1649 if ($timeFormat == 1) {
1650 $show24Hours = FALSE;
1653 //CRM-6664 -we are having time element name
1654 //in either flat string or an array format.
1655 $elementName = $name . '_time';
1656 if (substr($name, -1) == ']') {
1657 $elementName = substr($name, 0, strlen($name) - 1) . '_time]';
1660 $this->add('text', $elementName, ts('Time'), array('timeFormat' => $show24Hours));
1665 $this->addRule($name, ts('Please select %1', array(1 => $label)), 'required');
1666 if (!empty($attributes['addTime']) && !empty($attributes['addTimeRequired'])) {
1667 $this->addRule($elementName, ts('Please enter a time.'), 'required');
1673 * Function that will add date and time.
1675 public function addDateTime($name, $label, $required = FALSE, $attributes = NULL) {
1676 $addTime = array('addTime' => TRUE);
1677 if (is_array($attributes)) {
1678 $attributes = array_merge($attributes, $addTime);
1681 $attributes = $addTime;
1684 $this->addDate($name, $label, $required, $attributes);
1688 * Add a currency and money element to the form.
1690 public function addMoney(
1695 $addCurrency = TRUE,
1696 $currencyName = 'currency',
1697 $defaultCurrency = NULL,
1698 $freezeCurrency = FALSE
1700 $element = $this->add('text', $name, $label, $attributes, $required);
1701 $this->addRule($name, ts('Please enter a valid amount.'), 'money');
1704 $ele = $this->addCurrency($currencyName, NULL, TRUE, $defaultCurrency, $freezeCurrency);
1711 * Add currency element to the form.
1713 public function addCurrency(
1717 $defaultCurrency = NULL,
1718 $freezeCurrency = FALSE
1720 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
1721 $options = array('class' => 'crm-select2 eight');
1723 $currencies = array('' => '') +
$currencies;
1724 $options['placeholder'] = ts('- none -');
1726 $ele = $this->add('select', $name, $label, $currencies, $required, $options);
1727 if ($freezeCurrency) {
1730 if (!$defaultCurrency) {
1731 $config = CRM_Core_Config
::singleton();
1732 $defaultCurrency = $config->defaultCurrency
;
1734 $this->setDefaults(array($name => $defaultCurrency));
1738 * Create a single or multiple entity ref field.
1739 * @param string $name
1740 * @param string $label
1741 * @param array $props
1742 * Mix of html and widget properties, including:.
1743 * - select - params to give to select2 widget
1744 * - entity - defaults to contact
1745 * - create - can the user create a new entity on-the-fly?
1746 * Set to TRUE if entity is contact and you want the default profiles,
1747 * or pass in your own set of links. @see CRM_Core_BAO_UFGroup::getCreateLinks for format
1748 * note that permissions are checked automatically
1749 * - api - array of settings for the getlist api wrapper
1750 * note that it accepts a 'params' setting which will be passed to the underlying api
1751 * - placeholder - string
1753 * - class, etc. - other html properties
1754 * @param bool $required
1756 * @return HTML_QuickForm_Element
1758 public function addEntityRef($name, $label = '', $props = array(), $required = FALSE) {
1759 require_once "api/api.php";
1760 $config = CRM_Core_Config
::singleton();
1761 // Default properties
1762 $props['api'] = CRM_Utils_Array
::value('api', $props, array());
1763 $props['entity'] = _civicrm_api_get_entity_name_from_camel(CRM_Utils_Array
::value('entity', $props, 'contact'));
1764 $props['class'] = ltrim(CRM_Utils_Array
::value('class', $props, '') . ' crm-form-entityref');
1766 if ($props['entity'] == 'contact' && isset($props['create']) && !(CRM_Core_Permission
::check('edit all contacts') || CRM_Core_Permission
::check('add contacts'))) {
1767 unset($props['create']);
1770 $props['placeholder'] = CRM_Utils_Array
::value('placeholder', $props, $required ?
ts('- select %1 -', array(1 => ts(str_replace('_', ' ', $props['entity'])))) : ts('- none -'));
1772 $defaults = array();
1773 if (!empty($props['multiple'])) {
1774 $defaults['multiple'] = TRUE;
1776 $props['select'] = CRM_Utils_Array
::value('select', $props, array()) +
$defaults;
1778 $this->formatReferenceFieldAttributes($props);
1779 return $this->add('text', $name, $label, $props, $required);
1785 private function formatReferenceFieldAttributes(&$props) {
1786 $props['data-select-params'] = json_encode($props['select']);
1787 $props['data-api-params'] = $props['api'] ?
json_encode($props['api']) : NULL;
1788 $props['data-api-entity'] = $props['entity'];
1789 if (!empty($props['create'])) {
1790 $props['data-create-links'] = json_encode($props['create']);
1792 CRM_Utils_Array
::remove($props, 'multiple', 'select', 'api', 'entity', 'create');
1796 * Convert all date fields within the params to mysql date ready for the
1797 * BAO layer. In this case fields are checked against the $_datefields defined for the form
1798 * and if time is defined it is incorporated
1800 * @param array $params
1801 * Input params from the form.
1803 * @todo it would probably be better to work on $this->_params than a passed array
1804 * @todo standardise the format which dates are passed to the BAO layer in & remove date
1807 public function convertDateFieldsToMySQL(&$params) {
1808 foreach ($this->_dateFields
as $fieldName => $specs) {
1809 if (!empty($params[$fieldName])) {
1810 $params[$fieldName] = CRM_Utils_Date
::isoToMysql(
1811 CRM_Utils_Date
::processDate(
1812 $params[$fieldName],
1813 CRM_Utils_Array
::value("{$fieldName}_time", $params), TRUE)
1817 if (isset($specs['default'])) {
1818 $params[$fieldName] = date('YmdHis', strtotime($specs['default']));
1825 * @param $elementName
1827 public function removeFileRequiredRules($elementName) {
1828 $this->_required
= array_diff($this->_required
, array($elementName));
1829 if (isset($this->_rules
[$elementName])) {
1830 foreach ($this->_rules
[$elementName] as $index => $ruleInfo) {
1831 if ($ruleInfo['type'] == 'uploadedfile') {
1832 unset($this->_rules
[$elementName][$index]);
1835 if (empty($this->_rules
[$elementName])) {
1836 unset($this->_rules
[$elementName]);
1842 * Function that can be defined in Form to override or.
1843 * perform specific action on cancel action
1845 public function cancelAction() {
1849 * Helper function to verify that required fields have been filled.
1850 * Typically called within the scope of a FormRule function
1852 public static function validateMandatoryFields($fields, $values, &$errors) {
1853 foreach ($fields as $name => $fld) {
1854 if (!empty($fld['is_required']) && CRM_Utils_System
::isNull(CRM_Utils_Array
::value($name, $values))) {
1855 $errors[$name] = ts('%1 is a required field.', array(1 => $fld['title']));
1861 * Get contact if for a form object. Prioritise
1862 * - cid in URL if 0 (on behalf on someoneelse)
1863 * (@todo consider setting a variable if onbehalf for clarity of downstream 'if's
1864 * - logged in user id if it matches the one in the cid in the URL
1865 * - contact id validated from a checksum from a checksum
1866 * - cid from the url if the caller has ACL permission to view
1867 * - fallback is logged in user (or ? NULL if no logged in user) (@todo wouldn't 0 be more intuitive?)
1871 protected function setContactID() {
1872 $tempID = CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
1873 if (isset($this->_params
) && isset($this->_params
['select_contact_id'])) {
1874 $tempID = $this->_params
['select_contact_id'];
1876 if (isset($this->_params
, $this->_params
[0]) && !empty($this->_params
[0]['select_contact_id'])) {
1877 // event form stores as an indexed array, contribution form not so much...
1878 $tempID = $this->_params
[0]['select_contact_id'];
1881 // force to ignore the authenticated user
1882 if ($tempID === '0' ||
$tempID === 0) {
1883 // we set the cid on the form so that this will be retained for the Confirm page
1884 // in the multi-page form & prevent us returning the $userID when this is called
1886 // we don't really need to set it when $tempID is set because the params have that stored
1887 $this->set('cid', 0);
1888 return (int) $tempID;
1891 $userID = $this->getLoggedInUserContactID();
1893 if (!is_null($tempID) && $tempID === $userID) {
1894 return (int) $userID;
1897 //check if this is a checksum authentication
1898 $userChecksum = CRM_Utils_Request
::retrieve('cs', 'String', $this);
1899 if ($userChecksum) {
1900 //check for anonymous user.
1901 $validUser = CRM_Contact_BAO_Contact_Utils
::validChecksum($tempID, $userChecksum);
1906 // check if user has permission, CRM-12062
1907 elseif ($tempID && CRM_Contact_BAO_Contact_Permission
::allow($tempID)) {
1911 return is_numeric($userID) ?
$userID : NULL;
1914 public function getContactID() {
1915 return $this->setContactID();
1919 * Get the contact id of the logged in user.
1921 public function getLoggedInUserContactID() {
1922 // check if the user is logged in and has a contact ID
1923 $session = CRM_Core_Session
::singleton();
1924 return $session->get('userID');
1928 * Add autoselector field -if user has permission to view contacts
1929 * If adding this to a form you also need to add to the tpl e.g
1931 * {if !empty($selectable)}
1932 * <div class="crm-summary-row">
1933 * <div class="crm-label">{$form.select_contact.label}</div>
1934 * <div class="crm-content">
1935 * {$form.select_contact.html}
1940 * @param array $profiles
1941 * Ids of profiles that are on the form (to be autofilled).
1942 * @param array $autoCompleteField
1946 * - url (for ajax lookup)
1948 * @todo add data attributes so we can deal with multiple instances on a form
1950 public function addAutoSelector($profiles = array(), $autoCompleteField = array()) {
1951 $autoCompleteField = array_merge(array(
1952 'id_field' => 'select_contact_id',
1953 'placeholder' => ts('Select someone else ...'),
1954 'show_hide' => TRUE,
1955 'api' => array('params' => array('contact_type' => 'Individual')),
1956 ), $autoCompleteField);
1958 if ($this->canUseAjaxContactLookups()) {
1959 $this->assign('selectable', $autoCompleteField['id_field']);
1960 $this->addEntityRef($autoCompleteField['id_field'], NULL, array(
1961 'placeholder' => $autoCompleteField['placeholder'],
1962 'api' => $autoCompleteField['api'],
1965 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'js/AlternateContactSelector.js', 1, 'html-header')
1967 'form' => array('autocompletes' => $autoCompleteField),
1968 'ids' => array('profile' => $profiles),
1975 public function canUseAjaxContactLookups() {
1976 if (0 < (civicrm_api3('contact', 'getcount', array('check_permissions' => 1))) &&
1977 CRM_Core_Permission
::check(array(array('access AJAX API', 'access CiviCRM')))
1984 * Add the options appropriate to cid = zero - ie. autocomplete
1986 * @todo there is considerable code duplication between the contribution forms & event forms. It is apparent
1987 * that small pieces of duplication are not being refactored into separate functions because their only shared parent
1988 * is this form. Inserting a class FrontEndForm.php between the contribution & event & this class would allow functions like this
1989 * and a dozen other small ones to be refactored into a shared parent with the reduction of much code duplication
1991 * @param $onlinePaymentProcessorEnabled
1993 public function addCIDZeroOptions($onlinePaymentProcessorEnabled) {
1994 $this->assign('nocid', TRUE);
1995 $profiles = array();
1996 if ($this->_values
['custom_pre_id']) {
1997 $profiles[] = $this->_values
['custom_pre_id'];
1999 if ($this->_values
['custom_post_id']) {
2000 $profiles = array_merge($profiles, (array) $this->_values
['custom_post_id']);
2002 if ($onlinePaymentProcessorEnabled) {
2003 $profiles[] = 'billing';
2005 if (!empty($this->_values
)) {
2006 $this->addAutoSelector($profiles);
2011 * Set default values on form for given contact (or no contact defaults)
2013 * @param mixed $profile_id
2014 * (can be id, or profile name).
2015 * @param int $contactID
2019 public function getProfileDefaults($profile_id = 'Billing', $contactID = NULL) {
2021 $defaults = civicrm_api3('profile', 'getsingle', array(
2022 'profile_id' => (array) $profile_id,
2023 'contact_id' => $contactID,
2027 catch (Exception
$e) {
2028 // the try catch block gives us silent failure -not 100% sure this is a good idea
2029 // as silent failures are often worse than noisy ones
2035 * Sets form attribute.
2038 public function preventAjaxSubmit() {
2039 $this->setAttribute('data-no-ajax-submit', 'true');
2043 * Sets form attribute.
2046 public function allowAjaxSubmit() {
2047 $this->removeAttribute('data-no-ajax-submit');
2051 * Sets page title based on entity and action.
2052 * @param string $entityLabel
2054 public function setPageTitle($entityLabel) {
2055 switch ($this->_action
) {
2056 case CRM_Core_Action
::ADD
:
2057 CRM_Utils_System
::setTitle(ts('New %1', array(1 => $entityLabel)));
2060 case CRM_Core_Action
::UPDATE
:
2061 CRM_Utils_System
::setTitle(ts('Edit %1', array(1 => $entityLabel)));
2064 case CRM_Core_Action
::VIEW
:
2065 case CRM_Core_Action
::PREVIEW
:
2066 CRM_Utils_System
::setTitle(ts('View %1', array(1 => $entityLabel)));
2069 case CRM_Core_Action
::DELETE
:
2070 CRM_Utils_System
::setTitle(ts('Delete %1', array(1 => $entityLabel)));
2076 * Create a chain-select target field. All settings are optional; the defaults usually work.
2078 * @param string $elementName
2079 * @param array $settings
2081 * @return HTML_QuickForm_Element
2083 public function addChainSelect($elementName, $settings = array()) {
2084 $props = $settings +
= array(
2085 'control_field' => str_replace(array('state_province', 'StateProvince', 'county', 'County'), array(
2091 'data-callback' => strpos($elementName, 'rovince') ?
'civicrm/ajax/jqState' : 'civicrm/ajax/jqCounty',
2092 'label' => strpos($elementName, 'rovince') ?
ts('State/Province') : ts('County'),
2093 'data-empty-prompt' => strpos($elementName, 'rovince') ?
ts('Choose country first') : ts('Choose state first'),
2094 'data-none-prompt' => ts('- N/A -'),
2095 'multiple' => FALSE,
2096 'required' => FALSE,
2097 'placeholder' => empty($settings['required']) ?
ts('- none -') : ts('- select -'),
2099 CRM_Utils_Array
::remove($props, 'label', 'required', 'control_field');
2100 $props['class'] = (empty($props['class']) ?
'' : "{$props['class']} ") . 'crm-select2';
2101 $props['data-select-prompt'] = $props['placeholder'];
2102 $props['data-name'] = $elementName;
2104 $this->_chainSelectFields
[$settings['control_field']] = $elementName;
2106 // Passing NULL instead of an array of options
2107 // CRM-15225 - normally QF will reject any selected values that are not part of the field's options, but due to a
2108 // quirk in our patched version of HTML_QuickForm_select, this doesn't happen if the options are NULL
2109 // which seems a bit dirty but it allows our dynamically-popuplated select element to function as expected.
2110 return $this->add('select', $elementName, $settings['label'], NULL, $settings['required'], $props);
2114 * Set options and attributes for chain select fields based on the controlling field's value
2116 private function preProcessChainSelectFields() {
2117 foreach ($this->_chainSelectFields
as $control => $target) {
2118 // The 'target' might get missing if extensions do removeElement() in a form hook.
2119 if ($this->elementExists($target)) {
2120 $targetField = $this->getElement($target);
2121 $targetType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ?
'county' : 'stateProvince';
2123 // If the control field is on the form, setup chain-select and dynamically populate options
2124 if ($this->elementExists($control)) {
2125 $controlField = $this->getElement($control);
2126 $controlType = $targetType == 'county' ?
'stateProvince' : 'country';
2128 $targetField->setAttribute('class', $targetField->getAttribute('class') . ' crm-chain-select-target');
2130 $css = (string) $controlField->getAttribute('class');
2131 $controlField->updateAttributes(array(
2132 'class' => ($css ?
"$css " : 'crm-select2 ') . 'crm-chain-select-control',
2133 'data-target' => $target,
2135 $controlValue = $controlField->getValue();
2136 if ($controlValue) {
2137 $options = CRM_Core_BAO_Location
::getChainSelectValues($controlValue, $controlType, TRUE);
2139 $targetField->setAttribute('placeholder', $targetField->getAttribute('data-none-prompt'));
2143 $targetField->setAttribute('placeholder', $targetField->getAttribute('data-empty-prompt'));
2144 $targetField->setAttribute('disabled', 'disabled');
2147 // Control field not present - fall back to loading default options
2149 $options = CRM_Core_PseudoConstant
::$targetType();
2151 if (!$targetField->getAttribute('multiple')) {
2152 $options = array('' => $targetField->getAttribute('placeholder')) +
$options;
2153 $targetField->removeAttribute('placeholder');
2155 $targetField->_options
= array();
2156 $targetField->loadArray($options);
2162 * Validate country / state / county match and suppress unwanted "required" errors
2164 private function validateChainSelectFields() {
2165 foreach ($this->_chainSelectFields
as $control => $target) {
2166 if ($this->elementExists($control) && $this->elementExists($target)) {
2167 $controlValue = (array) $this->getElementValue($control);
2168 $targetField = $this->getElement($target);
2169 $controlType = $targetField->getAttribute('data-callback') == 'civicrm/ajax/jqCounty' ?
'stateProvince' : 'country';
2170 $targetValue = array_filter((array) $targetField->getValue());
2171 if ($targetValue ||
$this->getElementError($target)) {
2172 $options = CRM_Core_BAO_Location
::getChainSelectValues($controlValue, $controlType, TRUE);
2174 if (!array_intersect($targetValue, array_keys($options))) {
2175 $this->setElementError($target, $controlType == 'country' ?
ts('State/Province does not match the selected Country') : ts('County does not match the selected State/Province'));
2177 } // Suppress "required" error for field if it has no options
2178 elseif (!$options) {
2179 $this->setElementError($target, NULL);