3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
37 * Business objects for managing custom data fields.
40 class CRM_Core_BAO_CustomField
extends CRM_Core_DAO_CustomField
{
43 * Array for valid combinations of data_type & descriptions
48 public static $_dataType = NULL;
51 * Array for valid combinations of data_type & html_type
56 public static $_dataToHtml = NULL;
59 * Array to hold (formatted) fields for import
64 public static $_importFields = NULL;
67 * Build and retrieve the list of data types and descriptions
71 * @return array Data type => Description
75 static function &dataType() {
76 if (!(self
::$_dataType)) {
77 self
::$_dataType = array(
78 'String' => ts('Alphanumeric'),
79 'Int' => ts('Integer'),
80 'Float' => ts('Number'),
81 'Money' => ts('Money'),
84 'Boolean' => ts('Yes or No'),
85 'StateProvince' => ts('State/Province'),
86 'Country' => ts('Country'),
89 'ContactReference' => ts('Contact Reference'),
92 return self
::$_dataType;
95 static function dataToHtml() {
96 if (!self
::$_dataToHtml) {
97 self
::$_dataToHtml = array(
99 'Text' => 'Text', 'Select' => 'Select',
100 'Radio' => 'Radio', 'CheckBox' => 'CheckBox',
101 'Multi-Select' => 'Multi-Select',
102 'AdvMulti-Select' => 'AdvMulti-Select',
103 'Autocomplete-Select' => 'Autocomplete-Select',
105 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
106 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
107 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
108 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
109 array('Date' => 'Select Date'),
110 array('Radio' => 'Radio'),
111 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
112 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
113 array('File' => 'File'),
114 array('Link' => 'Link'),
115 array('ContactReference' => 'Autocomplete-Select'),
118 return self
::$_dataToHtml;
122 * takes an associative array and creates a custom field object
124 * This function is invoked from within the web form layer and also from the api layer
126 * @param array $params (reference) an assoc array of name/value pairs
128 * @return object CRM_Core_DAO_CustomField object
132 static function create(&$params) {
133 $origParams = array_merge(array(), $params);
135 if (!isset($params['id'])) {
136 if (!isset($params['column_name'])) {
137 // if add mode & column_name not present, calculate it.
138 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
140 if (!isset($params['name'])) {
141 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
145 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
150 $columnName = $params['column_name'];
153 //as during create if field is_searchable we had created index.
154 if (CRM_Utils_Array
::value('id', $params)) {
155 $indexExist = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
158 switch (CRM_Utils_Array
::value('html_type', $params)){
160 if(empty($params['date_format'])){
161 $config = CRM_Core_Config
::singleton();
162 $params['date_format'] = $config->dateInputFormat
;
166 case 'AdvMulti-Select':
168 if (isset($params['default_checkbox_option'])) {
169 $tempArray = array_keys($params['default_checkbox_option']);
170 $defaultArray = array();
171 foreach ($tempArray as $k => $v) {
172 if ($params['option_value'][$v]) {
173 $defaultArray[] = $params['option_value'][$v];
177 if (!empty($defaultArray)) {
178 // also add the seperator before and after the value per new conventio (CRM-1604)
179 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
183 if (CRM_Utils_Array
::value('default_option', $params)
184 && isset($params['option_value'][$params['default_option']])
186 $params['default_value'] = $params['option_value'][$params['default_option']];
192 $transaction = new CRM_Core_Transaction();
193 // create any option group & values if required
194 if ($params['html_type'] != 'Text' &&
195 in_array($params['data_type'], array(
196 'String', 'Int', 'Float', 'Money'))
199 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
200 $params['custom_group_id'],
205 if ($params['option_type'] == 1) {
206 // first create an option group for this custom group
207 $optionGroup = new CRM_Core_DAO_OptionGroup();
208 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
209 $optionGroup->title
= $params['label'];
210 $optionGroup->is_active
= 1;
211 $optionGroup->save();
212 $params['option_group_id'] = $optionGroup->id
;
213 if(!empty($params['option_value']) && is_array($params['option_value'])){
214 foreach ($params['option_value'] as $k => $v) {
215 if (strlen(trim($v))) {
216 $optionValue = new CRM_Core_DAO_OptionValue();
217 $optionValue->option_group_id
= $optionGroup->id
;
218 $optionValue->label
= $params['option_label'][$k];
219 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$k]);
220 switch ($params['data_type']) {
222 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($v);
226 $optionValue->value
= intval($v);
230 $optionValue->value
= floatval($v);
234 $optionValue->value
= trim($v);
237 $optionValue->weight
= $params['option_weight'][$k];
238 $optionValue->is_active
= CRM_Utils_Array
::value($k, $params['option_status'], FALSE);
239 $optionValue->save();
246 // check for orphan option groups
247 if (CRM_Utils_Array
::value('option_group_id', $params)) {
248 if (CRM_Utils_Array
::value('id', $params)) {
249 self
::fixOptionGroups($params['id'], $params['option_group_id']);
252 // if we dont have a default value
253 // retrive it from one of the other custom fields which use this option group
254 if (!CRM_Utils_Array
::value('default_value', $params)) {
255 //don't insert only value separator as default value, CRM-4579
256 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
260 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
263 $params['default_value'] = $defaultValue;
268 // since we need to save option group id :)
269 if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
270 $params['attributes'] = 'rows=4, cols=60';
273 $customField = new CRM_Core_DAO_CustomField();
274 $customField->copyValues($params);
275 $customField->is_required
= CRM_Utils_Array
::value('is_required', $params, FALSE);
276 $customField->is_searchable
= CRM_Utils_Array
::value('is_searchable', $params, FALSE);
277 $customField->is_search_range
= CRM_Utils_Array
::value('is_search_range', $params, FALSE);
278 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, FALSE);
279 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
280 $customField->save();
282 // make sure all values are present in the object for further processing
283 $customField->find(TRUE);
285 //create/drop the index when we toggle the is_searchable flag
286 if (CRM_Utils_Array
::value('id', $params)) {
287 self
::createField($customField, 'modify', $indexExist);
290 if (!isset($origParams['column_name'])) {
291 $columnName .= "_{$customField->id}";
292 $params['column_name'] = $columnName;
294 $customField->column_name
= $columnName;
295 $customField->save();
296 // make sure all values are present in the object
297 $customField->find(TRUE);
299 self
::createField($customField, 'add');
302 // complete transaction
303 $transaction->commit();
305 CRM_Utils_System
::flushCache();
311 * Takes a bunch of params that are needed to match certain criteria and
312 * retrieves the relevant objects. Typically the valid params are only
313 * contact_id. We'll tweak this function to be more full featured over a period
314 * of time. This is the inverse function of create. It also stores all the retrieved
315 * values in the default array
317 * @param array $params (reference ) an assoc array of name/value pairs
318 * @param array $defaults (reference ) an assoc array to hold the flattened values
320 * @return object CRM_Core_DAO_CustomField object
324 static function retrieve(&$params, &$defaults) {
325 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
329 * update the is_active flag in the db
331 * @param int $id Id of the database record
332 * @param boolean $is_active Value we want to set the is_active field
334 * @return Object DAO object on sucess, null otherwise
339 static function setIsActive($id, $is_active) {
341 CRM_Utils_System
::flushCache();
343 //enable-disable CustomField
344 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
345 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
349 * Get the field title.
351 * @param int $id id of field.
353 * @return string name
359 public static function getTitle($id) {
360 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
364 * Store and return an array of all active custom fields.
366 * @param string $customDataType type of Custom Data
367 * @param boolean $showAll If true returns all fields (includes disabled fields)
368 * @param boolean $inline If true returns all inline fields (includes disabled fields)
369 * @param int $customDataSubType Custom Data sub type value
370 * @param int $customDataSubName Custom Data sub name value
371 * @param boolean $onlyParent return only top level custom data, for eg, only Participant and ignore subname and subtype
372 * @param boolean $onlySubType return only custom data for subtype
373 * @param boolean $checkPermission if false, do not include permissioning clause
375 * @return array $fields - an array of active custom fields.
380 public static function &getFields($customDataType = 'Individual',
383 $customDataSubType = NULL,
384 $customDataSubName = NULL,
386 $onlySubType = FALSE,
387 $checkPermission = TRUE
389 if ($customDataType && !is_array($customDataType)) {
391 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
392 // This is the case when getFieldsForImport() requires fields
393 // limited strictly to a subtype.
394 $customDataSubType = $customDataType;
395 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
399 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
400 // this makes the method flexible to support retrieving fields
401 // for multiple extends value.
402 $customDataType = array($customDataType);
406 if ($customDataSubType && !is_array($customDataSubType)) {
407 $customDataSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
408 trim($customDataSubType, CRM_Core_DAO
::VALUE_SEPARATOR
)
412 if (is_array($customDataType)) {
413 $cacheKey = implode('_', $customDataType);
416 $cacheKey = $customDataType;
419 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
420 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
421 $cacheKey .= $showAll ?
'_1' : '_0';
422 $cacheKey .= $inline ?
'_1_' : '_0_';
423 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
424 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
425 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
427 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
429 // also get the permission stuff here
430 if ($checkPermission) {
431 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
436 $permissionClause = '(1)';
439 // lets md5 permission clause and take first 8 characters
440 $cacheKey .= substr(md5($permissionClause), 0, 8);
442 if (strlen($cacheKey) > 40) {
443 $cacheKey = md5($cacheKey);
446 if (!self
::$_importFields ||
447 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
449 if (!self
::$_importFields) {
450 self
::$_importFields = array();
453 // check if we can retrieve from database cache
454 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
456 if ($fields === NULL) {
457 $cfTable = self
::getTableName();
460 if (is_array($customDataType)) {
462 foreach ($customDataType as $dataType) {
463 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
464 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
465 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
468 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
470 $value = $value ?
$value . ", {$val}" : $val;
474 $extends = "AND $cgTable.extends IN ( $value ) ";
478 if (!empty($customDataType) && empty($extends)) {
479 // $customDataType did not include any customizable/extendable entities.
480 self
::$_importFields[$cacheKey] = array();
481 return self
::$_importFields[$cacheKey];
485 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
488 $query = "SELECT $cfTable.id, $cfTable.label,
492 $cfTable.default_value,
493 $cfTable.options_per_line, $cfTable.text_length,
494 $cfTable.custom_group_id,
495 $cgTable.extends, $cfTable.is_search_range,
496 $cgTable.extends_entity_column_value,
497 $cgTable.extends_entity_column_id,
499 $cfTable.option_group_id,
500 $cfTable.date_format,
501 $cfTable.time_format,
505 ON $cfTable.custom_group_id = $cgTable.id
509 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
513 $query .= " AND $cgTable.style = 'Inline' ";
516 //get the custom fields for specific type in
517 //combination with fields those support any type.
518 if (!empty($customDataSubType)) {
519 $subtypeClause = array();
520 foreach ($customDataSubType as $subtype) {
521 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
522 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
525 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
527 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
530 if ($customDataSubName) {
531 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
534 // also get the permission stuff here
535 if ($checkPermission) {
536 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
541 $permissionClause = '(1)';
544 $query .= " $extends AND $permissionClause
545 ORDER BY $cgTable.weight, $cgTable.title,
546 $cfTable.weight, $cfTable.label";
548 $dao = CRM_Core_DAO
::executeQuery($query);
551 while (($dao->fetch()) != NULL) {
552 $fields[$dao->id
]['label'] = $dao->label
;
553 $fields[$dao->id
]['groupTitle'] = $dao->title
;
554 $fields[$dao->id
]['data_type'] = $dao->data_type
;
555 $fields[$dao->id
]['html_type'] = $dao->html_type
;
556 $fields[$dao->id
]['default_value'] = $dao->default_value
;
557 $fields[$dao->id
]['text_length'] = $dao->text_length
;
558 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
559 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
560 $fields[$dao->id
]['extends'] = $dao->extends;
561 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
562 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
563 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
564 $fields[$dao->id
]['is_view'] = $dao->is_view
;
565 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
566 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
567 $fields[$dao->id
]['date_format'] = $dao->date_format
;
568 $fields[$dao->id
]['time_format'] = $dao->time_format
;
571 CRM_Core_BAO_Cache
::setItem($fields,
573 "custom importableFields $cacheKey"
576 self
::$_importFields[$cacheKey] = $fields;
579 return self
::$_importFields[$cacheKey];
583 * Return the field ids and names (with groups) for import purpose.
585 * @param int $contactType Contact type
586 * @param boolean $showAll If true returns all fields (includes disabled fields)
587 * @param boolean $onlyParent return fields ONLY related to basic types
588 * @param boolean $search when called from search and multiple records need to be returned
589 * @param boolean $checkPermission if false, do not include permissioning clause
591 * @return array $fields -
596 public static function &getFieldsForImport($contactType = 'Individual',
600 $checkPermission = TRUE,
601 $withMultiple = FALSE
603 // Note: there are situations when we want getFieldsForImport() return fields related
604 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
605 $fields = &self
::getFields($contactType,
615 $importableFields = array();
616 foreach ($fields as $id => $values) {
617 // for now we should not allow multiple fields in profile / export etc, hence unsetting
619 (CRM_Utils_Array
::value('is_multiple', $values) && !$withMultiple)
624 /* generate the key for the fields array */
628 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
629 $importableFields[$key] = array(
631 'title' => CRM_Utils_Array
::value('label', $values),
632 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
634 'custom_field_id' => $id,
635 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
636 'data_type' => CRM_Utils_Array
::value('data_type', $values),
637 'html_type' => CRM_Utils_Array
::value('html_type', $values),
638 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
641 // CRM-6681, pass date and time format when html_type = Select Date
642 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
643 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
644 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
648 return $importableFields;
652 * Get the field id from an import key
654 * @param string $key The key to parse
656 * @return int|null The id (if exists)
660 public static function getKeyID($key, $all = FALSE) {
662 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
669 CRM_Utils_Array
::value(2, $match),
678 * Use the cache to get all values of a specific custom field
680 * @param int $fieldID the custom field ID
682 * @return object $field the field object
686 static function getFieldObject($fieldID) {
687 $field = new CRM_Core_DAO_CustomField();
689 // check if we can get the field values from the system cache
690 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
691 $cache = CRM_Utils_Cache
::singleton();
692 $fieldValues = $cache->get($cacheKey);
693 if (empty($fieldValues)) {
694 $field->id
= $fieldID;
695 if (!$field->find(TRUE)) {
696 CRM_Core_Error
::fatal();
699 $fieldValues = array();
700 CRM_Core_DAO
::storeValues($field, $fieldValues);
702 $cache->set($cacheKey, $fieldValues);
705 $field->copyValues($fieldValues);
712 * This function for building custom fields
714 * @param object $qf form object (reference)
715 * @param string $elementName name of the custom field
716 * @param boolean $inactiveNeeded
717 * @param boolean $userRequired true if required else false
718 * @param boolean $search true if used for search else false
719 * @param string $label label for custom field
724 public static function addQuickFormElement(&$qf,
727 $inactiveNeeded = FALSE,
732 // we use $_POST directly, since we dont want to use session memory, CRM-4677
733 if (isset($_POST['_qf_Relationship_refresh']) &&
734 ($_POST['_qf_Relationship_refresh'] == 'Search' ||
735 $_POST['_qf_Relationship_refresh'] == 'Search Again'
738 $useRequired = FALSE;
741 $field = self
::getFieldObject($fieldId);
743 // Fixed for Issue CRM-2183
744 if ($field->html_type
== 'TextArea' && $search) {
745 $field->html_type
= 'Text';
748 if (!isset($label)) {
749 $label = $field->label
;
753 * at some point in time we might want to split the below into small functions
756 switch ($field->html_type
) {
758 if ($field->is_search_range
&& $search) {
759 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
760 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
763 $element = &$qf->add(strtolower($field->html_type
), $elementName, $label,
765 $useRequired && !$search
772 if ($field->note_rows
) {
773 $attributes .= 'rows=' . $field->note_rows
;
776 $attributes .= 'rows=4';
778 if ($field->note_columns
) {
779 $attributes .= ' cols=' . $field->note_columns
;
782 $attributes .= ' cols=60';
784 if ($field->text_length
) {
785 $attributes .= ' maxlength=' . $field->text_length
;
787 $element = &$qf->add(strtolower($field->html_type
),
791 $useRequired && !$search
796 if ($field->is_search_range
&& $search) {
797 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
799 'format' => $field->date_format
,
800 'timeFormat' => $field->time_format
,
801 'startOffset' => $field->start_date_years
,
802 'endOffset' => $field->end_date_years
,
806 $qf->addDate($elementName . '_to', ts('To'), FALSE,
808 'format' => $field->date_format
,
809 'timeFormat' => $field->time_format
,
810 'startOffset' => $field->start_date_years
,
811 'endOffset' => $field->end_date_years
,
816 $required = $useRequired && !$search;
818 $qf->addDate($elementName, $label, $required, array(
819 'format' => $field->date_format
,
820 'timeFormat' => $field->time_format
,
821 'startOffset' => $field->start_date_years
,
822 'endOffset' => $field->end_date_years
,
829 if ($field->data_type
!= 'Boolean') {
830 $customOption = &CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
831 $field->option_group_id
833 foreach ($customOption as $v => $l) {
834 $choice[] = $qf->createElement('radio', NULL, '', $l, (string)$v, $field->attributes
);
836 $qf->addGroup($choice, $elementName, $label);
839 $choice[] = $qf->createElement('radio', NULL, '', ts('Yes'), '1', $field->attributes
);
840 $choice[] = $qf->createElement('radio', NULL, '', ts('No'), '0', $field->attributes
);
841 $qf->addGroup($choice, $elementName, $label);
843 if ($useRequired && !$search) {
844 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
849 $selectOption = &CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
850 $field->option_group_id
852 $qf->add('select', $elementName, $label,
854 '' => ts('- select -')) +
$selectOption,
855 $useRequired && !$search
859 //added for select multiple
861 case 'AdvMulti-Select':
862 $selectOption = &CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
863 $field->option_group_id
866 count($selectOption) > 1
868 $selectOption['CiviCRM_OP_OR'] = ts('Select to match ANY; unselect to match ALL');
871 $include =& $qf->addElement(
874 $label, $selectOption,
878 'class' => 'advmultiselect',
882 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
883 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
885 if ($useRequired && !$search) {
886 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
891 $selectOption = &CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
892 $field->option_group_id
895 count($selectOption) > 1
897 $selectOption['CiviCRM_OP_OR'] = ts('Select to match ANY; unselect to match ALL');
899 $qf->addElement('select', $elementName, $label, $selectOption, array('size' => '5', 'multiple'));
901 if ($useRequired && !$search) {
902 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
907 $customOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
908 $field->option_group_id
911 foreach ($customOption as $v => $l) {
912 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l);
917 $check[] = &$qf->addElement('advcheckbox', 'CiviCRM_OP_OR', NULL, ts('Check to match ANY; uncheck to match ALL'));
919 $qf->addGroup($check, $elementName, $label);
920 if ($useRequired && !$search) {
921 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
926 // we should not build upload file in search mode
931 strtolower($field->html_type
),
935 $useRequired && !$search
937 $qf->addUploadElement($elementName);
940 case 'Select State/Province':
942 $stateOption = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::stateProvince();
943 $qf->add('select', $elementName, $label, $stateOption,
944 $useRequired && !$search
948 case 'Multi-Select State/Province':
949 //Add Multi-select State/Province
950 $stateOption = CRM_Core_PseudoConstant
::stateProvince();
952 $qf->addElement('select', $elementName, $label, $stateOption, array('size' => '5', 'multiple'));
953 if ($useRequired && !$search) {
954 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
958 case 'Select Country':
960 $countryOption = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::country();
961 $qf->add('select', $elementName, $label, $countryOption,
962 $useRequired && !$search
966 case 'Multi-Select Country':
968 $countryOption = CRM_Core_PseudoConstant
::country();
969 $qf->addElement('select', $elementName, $label, $countryOption, array('size' => '5', 'multiple'));
970 if ($useRequired && !$search) {
971 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
975 case 'RichTextEditor':
976 $attributes = array('rows' => $field->note_rows
, 'cols' => $field->note_columns
);
977 if ($field->text_length
) {
978 $attributes['maxlength'] = $field->text_length
;
980 $qf->addWysiwyg($elementName, $label, $attributes, $search);
983 case 'Autocomplete-Select':
984 $qf->add('text', $elementName, $label, $field->attributes
,
985 $useRequired && !$search
988 $hiddenEleName = $elementName . '_id';
989 if (substr($elementName, -1) == ']') {
990 $hiddenEleName = substr($elementName, 0, -1) . '_id]';
992 $qf->addElement('hidden', $hiddenEleName, '', array('id' => str_replace(array(']', '['), array('', '_'), $hiddenEleName)));
994 static $customUrls = array();
995 if ($field->data_type
== 'ContactReference') {
996 //$urlParams = "className=CRM_Contact_Page_AJAX&fnName=getContactList&json=1&reset=1&context=customfield&id={$field->id}";
997 $urlParams = "context=customfield&id={$field->id}";
999 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1004 $actualElementValue = $qf->getSubmitValue($hiddenEleName);
1005 $qf->addRule($elementName, ts('Select a valid contact for %1.', array(1 => $label)), 'validContact', $actualElementValue);
1008 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/auto',
1009 "reset=1&ogid={$field->option_group_id}&cfid={$field->id}",
1012 $qf->addRule($elementName, ts('Select a valid value for %1.', array(1 => $label)),
1013 'autocomplete', array(
1014 'fieldID' => $field->id
,
1015 'optionGroupID' => $field->option_group_id
,
1020 $qf->assign('customUrls', $customUrls);
1024 switch ($field->data_type
) {
1026 // integers will have numeric rule applied to them.
1027 if ($field->is_search_range
&& $search) {
1028 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1029 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1032 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1037 if ($field->is_search_range
&& $search) {
1038 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1039 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1042 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1047 if ($field->is_search_range
&& $search) {
1048 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1049 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1052 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1062 'onfocus' => "if (!this.value) { this.value='http://';} else return false",
1063 'onblur' => "if ( this.value == 'http://') { this.value='';} else return false",
1065 $useRequired && !$search
1067 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1070 if ($field->is_view
&& !$search) {
1071 $qf->freeze($elementName);
1076 * Delete the Custom Field.
1078 * @param object $field - the field object
1086 public static function deleteField($field) {
1087 CRM_Utils_System
::flushCache();
1089 // first delete the custom option group and values associated with this field
1090 if ($field->option_group_id
) {
1091 //check if option group is related to any other field, if
1092 //not delete the option group and related option values
1093 self
::checkOptionGroup($field->option_group_id
);
1096 // next drop the column from the custom value table
1097 self
::createField($field, 'delete');
1100 CRM_Core_BAO_UFField
::delUFField($field->id
);
1101 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1107 * Given a custom field value, its id and the set of options
1108 * find the display value for this field
1110 * @param mixed $value the custom field value
1111 * @param int $id the custom field id
1112 * @param int $options the assoc array of option name/value pairs
1114 * @return string the display value
1119 static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1120 $option = &$options[$id];
1121 $attributes = &$option['attributes'];
1122 $html_type = $attributes['html_type'];
1123 $data_type = $attributes['data_type'];
1124 $format = CRM_Utils_Array
::value('format', $attributes);
1126 return self
::getDisplayValueCommon($value,
1136 static function getDisplayValueCommon($value,
1147 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1148 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1149 $html_type == 'Select' ||
1150 $html_type == 'CheckBox' ||
1151 $html_type == 'AdvMulti-Select' ||
1152 $html_type == 'Multi-Select'
1155 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1158 switch ($html_type) {
1160 if ($data_type == 'Boolean') {
1161 // Do not assume that if not yes means no.
1164 $display = ts('Yes');
1166 elseif ($value === '0') {
1167 $display = ts('No');
1171 $display = CRM_Utils_Array
::value($value, $option);
1175 case 'Autocomplete-Select':
1176 if ($data_type == 'ContactReference' &&
1179 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1182 $display = CRM_Utils_Array
::value($value, $option);
1187 $display = CRM_Utils_Array
::value($value, $option);
1191 case 'AdvMulti-Select':
1192 case 'Multi-Select':
1193 if (is_array($value)) {
1194 $checkedData = $value;
1197 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1198 substr($value, 1, -1)
1200 if ($html_type == 'CheckBox') {
1202 foreach ($checkedData as $v) {
1205 $checkedData = $newData;
1211 foreach ($checkedData as $key => $val) {
1212 if ($key === 'CiviCRM_OP_OR') {
1216 if ($html_type == 'CheckBox') {
1219 $v[] = CRM_Utils_Array
::value($key, $option);
1224 $v[] = CRM_Utils_Array
::value($val, $option);
1228 $display = implode(', ', $v);
1233 if (is_array($value)) {
1234 foreach ($value as $key => $val) {
1235 $display[$key] = CRM_Utils_Date
::customFormat($val);
1239 // remove time element display if time is not set
1240 if (empty($option['attributes']['time_format'])) {
1241 $value = substr($value, 0, 10);
1243 $display = CRM_Utils_Date
::customFormat($value);
1247 case 'Select State/Province':
1248 if (empty($value)) {
1252 $display = CRM_Core_PseudoConstant
::stateProvince($value);
1256 case 'Multi-Select State/Province':
1257 if (is_array($value)) {
1258 $checkedData = $value;
1261 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1262 substr($value, 1, -1)
1266 $states = CRM_Core_PseudoConstant
::stateProvince();
1268 foreach ($checkedData as $stateID) {
1272 $display .= $states[$stateID];
1276 case 'Select Country':
1277 if (empty($value)) {
1281 $display = CRM_Core_PseudoConstant
::country($value);
1285 case 'Multi-Select Country':
1286 if (is_array($value)) {
1287 $checkedData = $value;
1290 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1291 substr($value, 1, -1)
1295 $countries = CRM_Core_PseudoConstant
::country();
1297 foreach ($checkedData as $countryID) {
1301 $display .= $countries[$countryID];
1307 $url = self
::getFileURL($contactID, $fieldID, $value);
1309 $display = $url['file_url'];
1315 if (empty($value)) {
1319 $display = nl2br($value);
1324 if (empty($value)) {
1332 return $display ?
$display : $value;
1336 * Function to set default values for custom data used in profile
1338 * @params int $customFieldId custom field id
1339 * @params string $elementName custom field name
1340 * @params array $defaults associated array of fields
1341 * @params int $contactId contact id
1342 * @param int $mode profile mode
1343 * @param mixed $value if passed - dont fetch value from db,
1344 * just format the given value
1348 static function setProfileDefaults($customFieldId,
1355 //get the type of custom field
1356 $customField = new CRM_Core_BAO_CustomField();
1357 $customField->id
= $customFieldId;
1358 $customField->find(TRUE);
1361 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1362 $value = $customField->default_value
;
1366 if (!isset($value)) {
1367 $info = self
::getTableColumnGroup($customFieldId);
1368 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1369 $result = CRM_Core_DAO
::executeQuery($query);
1370 if ($result->fetch()) {
1371 $value = $result->value
;
1375 if ($customField->data_type
== 'Country') {
1377 $config = CRM_Core_Config
::singleton();
1378 if ($config->defaultContactCountry
) {
1379 $value = $config->defaultContactCountry();
1385 //set defaults if mode is registration
1386 if (!trim($value) &&
1388 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1390 $value = $customField->default_value
;
1393 if ($customField->data_type
== 'Money' && isset($value)) {
1394 $value = number_format($value, 2);
1396 switch ($customField->html_type
) {
1398 case 'AdvMulti-Select':
1399 case 'Multi-Select':
1400 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1401 $defaults[$elementName] = array();
1402 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1403 substr($value, 1, -1)
1405 foreach ($customOption as $val) {
1406 if (in_array($val['value'], $checkedValue)) {
1407 if ($customField->html_type
== 'CheckBox') {
1408 $defaults[$elementName][$val['value']] = 1;
1410 elseif ($customField->html_type
== 'Multi-Select' ||
1411 $customField->html_type
== 'AdvMulti-Select'
1413 $defaults[$elementName][$val['value']] = $val['value'];
1421 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1424 $customField->date_format
,
1425 $customField->time_format
1430 case 'Autocomplete-Select':
1431 if ($customField->data_type
== 'ContactReference') {
1432 if (is_numeric($value)) {
1433 $defaults[$elementName . '_id'] = $value;
1434 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1438 $label = CRM_Core_BAO_CustomOption
::getOptionLabel($customField->id
, $value);
1439 $defaults[$elementName . '_id'] = $value;
1440 $defaults[$elementName] = $label;
1445 $defaults[$elementName] = $value;
1449 static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE) {
1452 $params = array('id' => $cfID);
1453 $defaults = array();
1454 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1455 $columnName = $defaults['column_name'];
1457 //table name of custom data
1458 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1459 $defaults['custom_group_id'],
1463 //query to fetch id from civicrm_file
1464 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1465 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1470 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1475 $result['file_id'] = $fileID;
1477 if ($fileType == 'image/jpeg' ||
1478 $fileType == 'image/pjpeg' ||
1479 $fileType == 'image/gif' ||
1480 $fileType == 'image/x-png' ||
1481 $fileType == 'image/png'
1483 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1488 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1489 list($imageWidth, $imageHeight) = getimagesize($path);
1490 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1491 $url = CRM_Utils_System
::url('civicrm/file',
1492 "reset=1&id=$fileID&eid=$contactID",
1493 $absolute, NULL, TRUE, TRUE
1495 $result['file_url'] = "
1496 <a href=\"$url\" class='crm-image-popup'>
1497 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1499 // for non image files
1502 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1506 $url = CRM_Utils_System
::url('civicrm/file',
1507 "reset=1&id=$fileID&eid=$contactID",
1508 $absolute, NULL, TRUE, TRUE
1510 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1518 * Format custom fields before inserting
1520 * @param int $customFieldId custom field id
1521 * @param array $customFormatted formatted array
1522 * @param mix $value value of custom field
1523 * @param string $customFieldExtend custom field extends
1524 * @param int $customValueId custom option value id
1525 * @param int $entityId entity id (contribution, membership...)
1526 * @param boolean $inline consider inline custom groups only
1527 * @param boolean $checkPermission if false, do not include permissioning clause
1529 * @return array $customFormatted formatted custom field array
1532 static function formatCustomField($customFieldId, &$customFormatted, $value,
1533 $customFieldExtend, $customValueId = NULL,
1536 $checkPermission = TRUE
1538 //get the custom fields for the entity
1539 //subtype and basic type
1540 $customDataSubType = NULL;
1541 if (in_array($customFieldExtend,
1542 CRM_Contact_BAO_ContactType
::subTypes()
1544 // This is the case when getFieldsForImport() requires fields
1545 // of subtype and its parent.CRM-5143
1546 $customDataSubType = $customFieldExtend;
1547 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1550 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1560 if (!array_key_exists($customFieldId, $customFields)) {
1564 // return if field is a 'code' field
1565 if (CRM_Utils_Array
::value('is_view', $customFields[$customFieldId])) {
1569 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1571 if (is_array($customFieldExtend)) {
1572 $customFieldExtend = $customFieldExtend[0];
1574 if (!$customValueId &&
1575 // we always create new entites for is_multiple unless specified
1576 !$customFields[$customFieldId]['is_multiple'] &&
1582 WHERE entity_id={$entityId}";
1584 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1587 //fix checkbox, now check box always submits values
1588 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1590 // Note that only during merge this is not an array, and you can directly use value
1591 if (is_array($value)) {
1592 $selectedValues = array();
1593 foreach ($value as $selId => $val) {
1595 $selectedValues[] = $selId;
1598 if (!empty($selectedValues)) {
1599 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1601 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1610 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1611 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1614 // Note that only during merge this is not an array,
1615 // and you can directly use value, CRM-4385
1616 if (is_array($value)) {
1617 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1618 array_values($value)
1619 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1627 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1628 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1629 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1631 $customFields[$customFieldId]['data_type'] == 'String' &&
1632 !empty($customFields[$customFieldId]['text_length']) &&
1635 // lets make sure that value is less than the length, else we'll
1636 // be losing some data, CRM-7481
1637 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1638 // need to do a few things here
1640 // 1. lets find a new length
1641 $newLength = $customFields[$customFieldId]['text_length'];
1642 $minLength = strlen($value);
1643 while ($newLength < $minLength) {
1644 $newLength = $newLength * 2;
1647 // set the custom field meta data to have a length larger than value
1648 // alter the custom value table column to match this length
1649 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1654 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1655 if (!CRM_Utils_System
::isNull($value)) {
1656 $format = $customFields[$customFieldId]['date_format'];
1657 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1662 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1663 $customFields[$customFieldId]['data_type'] == 'Money'
1669 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1670 $value = CRM_Utils_Rule
::cleanMoney($value);
1674 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1675 $customFields[$customFieldId]['data_type'] == 'Country'
1685 if ($customFields[$customFieldId]['data_type'] == 'File') {
1686 if (empty($value)) {
1690 $config = CRM_Core_Config
::singleton();
1692 $fName = $value['name'];
1693 $mimeType = $value['type'];
1695 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1697 // rename this file to go into the secure directory
1698 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1699 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1703 if ($customValueId) {
1708 $params = array(1 => array($customValueId, 'Integer'));
1709 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1712 $fileDAO = new CRM_Core_DAO_File();
1715 $fileDAO->id
= $fileId;
1718 $fileDAO->uri
= $filename;
1719 $fileDAO->mime_type
= $mimeType;
1720 $fileDAO->upload_date
= date('Ymdhis');
1722 $fileId = $fileDAO->id
;
1726 if (!is_array($customFormatted)) {
1727 $customFormatted = array();
1730 if (!array_key_exists($customFieldId, $customFormatted)) {
1731 $customFormatted[$customFieldId] = array();
1735 if ($customValueId) {
1736 $index = $customValueId;
1739 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1740 $customFormatted[$customFieldId][$index] = array();
1742 $customFormatted[$customFieldId][$index] = array(
1743 'id' => $customValueId > 0 ?
$customValueId : NULL,
1745 'type' => $customFields[$customFieldId]['data_type'],
1746 'custom_field_id' => $customFieldId,
1747 'custom_group_id' => $groupID,
1748 'table_name' => $tableName,
1749 'column_name' => $columnName,
1750 'file_id' => $fileId,
1751 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1754 //we need to sort so that custom fields are created in the order of entry
1755 krsort($customFormatted[$customFieldId]);
1756 return $customFormatted;
1759 static function &defaultCustomTableSchema(&$params) {
1760 // add the id and extends_id
1762 'name' => $params['name'],
1763 'is_multiple' => $params['is_multiple'],
1764 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1768 'type' => 'int unsigned',
1771 'attributes' => 'AUTO_INCREMENT',
1772 'comment' => 'Default MySQL primary key',
1775 'name' => 'entity_id',
1776 'type' => 'int unsigned',
1778 'comment' => 'Table that this extends',
1779 'fk_table_name' => $params['extends_name'],
1780 'fk_field_name' => 'id',
1781 'fk_attributes' => 'ON DELETE CASCADE',
1786 if (!$params['is_multiple']) {
1787 $table['indexes'] = array(
1790 'field_name_1' => 'entity_id',
1797 static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1798 $tableName = CRM_Core_DAO
::getFieldValue(
1799 'CRM_Core_DAO_CustomGroup',
1800 $field->custom_group_id
,
1805 'table_name' => $tableName,
1806 'operation' => $operation,
1807 'name' => $field->column_name
,
1808 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1812 'required' => $field->is_required
,
1813 'searchable' => $field->is_searchable
,
1816 if ($operation == 'delete') {
1817 $fkName = "{$tableName}_{$field->column_name}";
1818 if (strlen($fkName) >= 48) {
1819 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1821 $params['fkName'] = $fkName;
1823 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1824 $params['fk_table_name'] = 'civicrm_country';
1825 $params['fk_field_name'] = 'id';
1826 $params['fk_attributes'] = 'ON DELETE SET NULL';
1828 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1829 $params['type'] = 'varchar(255)';
1831 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1832 $params['fk_table_name'] = 'civicrm_state_province';
1833 $params['fk_field_name'] = 'id';
1834 $params['fk_attributes'] = 'ON DELETE SET NULL';
1836 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1837 $params['type'] = 'varchar(255)';
1839 elseif ($field->data_type
== 'File') {
1840 $params['fk_table_name'] = 'civicrm_file';
1841 $params['fk_field_name'] = 'id';
1842 $params['fk_attributes'] = 'ON DELETE SET NULL';
1844 elseif ($field->data_type
== 'ContactReference') {
1845 $params['fk_table_name'] = 'civicrm_contact';
1846 $params['fk_field_name'] = 'id';
1847 $params['fk_attributes'] = 'ON DELETE SET NULL';
1849 if ($field->default_value
) {
1850 $params['default'] = "'{$field->default_value}'";
1853 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1857 * Determine whether it would be safe to move a field
1859 * @param int $fieldID FK to civicrm_custom_field
1860 * @param int $newGroupID FK to civicrm_custom_group
1865 static function _moveFieldValidate($fieldID, $newGroupID) {
1868 $field = new CRM_Core_DAO_CustomField();
1869 $field->id
= $fieldID;
1870 if (!$field->find(TRUE)) {
1871 $errors['fieldID'] = 'Invalid ID for custom field';
1875 $oldGroup = new CRM_Core_DAO_CustomGroup();
1876 $oldGroup->id
= $field->custom_group_id
;
1877 if (!$oldGroup->find(TRUE)) {
1878 $errors['fieldID'] = 'Invalid ID for old custom group';
1882 $newGroup = new CRM_Core_DAO_CustomGroup();
1883 $newGroup->id
= $newGroupID;
1884 if (!$newGroup->find(TRUE)) {
1885 $errors['newGroupID'] = 'Invalid ID for new custom group';
1891 FROM civicrm_custom_field a
1892 INNER JOIN civicrm_custom_field b
1894 AND a.label = b.label
1895 AND b.custom_group_id = %2
1898 1 => array($field->id
, 'Integer'),
1899 2 => array($newGroup->id
, 'Integer'),
1901 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1903 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1906 $tableName = $oldGroup->table_name
;
1907 $columnName = $field->column_name
;
1912 WHERE $columnName is not null
1914 $count = CRM_Core_DAO
::singleValueQuery($query,
1915 CRM_Core_DAO
::$_nullArray
1920 FROM civicrm_custom_group
1921 WHERE id IN ( %1, %2 )
1923 $params = array(1 => array($oldGroup->id
, 'Integer'),
1924 2 => array($newGroup->id
, 'Integer'),
1927 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1929 while ($dao->fetch()) {
1930 $extends[] = $dao->extends;
1932 if ($extends[0] != $extends[1]) {
1933 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1937 return empty($errors) ?
TRUE : $errors;
1941 * Move a custom data field from one group (table) to another
1943 * @param int $fieldID FK to civicrm_custom_field
1944 * @param int $newGroupID FK to civicrm_custom_group
1948 static function moveField($fieldID, $newGroupID) {
1949 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1950 if (TRUE !== $validation) {
1951 CRM_Core_Error
::fatal(implode(' ', $validation));
1953 $field = new CRM_Core_DAO_CustomField();
1954 $field->id
= $fieldID;
1957 $newGroup = new CRM_Core_DAO_CustomGroup();
1958 $newGroup->id
= $newGroupID;
1959 $newGroup->find(TRUE);
1961 $oldGroup = new CRM_Core_DAO_CustomGroup();
1962 $oldGroup->id
= $field->custom_group_id
;
1963 $oldGroup->find(TRUE);
1966 $add->custom_group_id
= $newGroup->id
;
1967 self
::createField($add, 'add');
1969 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1970 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1971 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1973 CRM_Core_DAO
::executeQuery($sql);
1976 $del->custom_group_id
= $oldGroup->id
;
1977 self
::createField($del, 'delete');
1981 CRM_Utils_System
::flushCache();
1985 * Get the database table name and column name for a custom field
1987 * @param int $fieldID - the fieldID of the custom field
1988 * @param boolean $force - force the sql to be run again (primarily used for tests)
1990 * @return array - fatal is fieldID does not exists, else array of tableName, columnName
1994 static function getTableColumnGroup($fieldID, $force = FALSE) {
1995 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
1996 $cache = CRM_Utils_Cache
::singleton();
1997 $fieldValues = $cache->get($cacheKey);
1998 if (empty($fieldValues) ||
$force) {
2000 SELECT cg.table_name, cf.column_name, cg.id
2001 FROM civicrm_custom_group cg,
2002 civicrm_custom_field cf
2003 WHERE cf.custom_group_id = cg.id
2005 $params = array(1 => array($fieldID, 'Integer'));
2006 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2008 if (!$dao->fetch()) {
2009 CRM_Core_Error
::fatal();
2012 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2013 $cache->set($cacheKey, $fieldValues);
2015 return $fieldValues;
2019 * Function to get custom option groups
2021 * @params array $includeFieldIds ids of custom fields for which
2022 * option groups must be included.
2024 * Currently this is required in the cases where option groups are to be included
2025 * for inactive fields : CRM-5369
2029 * @return $customOptionGroup
2032 public static function &customOptionGroup($includeFieldIds = NULL) {
2033 static $customOptionGroup = NULL;
2035 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2036 if ($cacheKey == 'force') {
2037 $customOptionGroup[$cacheKey] = NULL;
2040 if (!CRM_Utils_Array
::value($cacheKey, $customOptionGroup)) {
2041 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2043 //support for single as well as array format.
2044 if (!empty($includeFieldIds)) {
2045 if (is_array($includeFieldIds)) {
2046 $includeFieldIds = implode(',', $includeFieldIds);
2048 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2052 SELECT g.id, g.title
2053 FROM civicrm_option_group g
2054 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2055 WHERE {$whereClause}";
2057 $dao = CRM_Core_DAO
::executeQuery($query);
2058 while ($dao->fetch()) {
2059 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2063 return $customOptionGroup[$cacheKey];
2067 * Function to fix orphan groups
2069 * @params int $customFieldId custom field id
2070 * @params int $optionGroupId option group id
2077 static function fixOptionGroups($customFieldId, $optionGroupId) {
2078 // check if option group belongs to any custom Field else delete
2079 // get the current option group
2080 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2084 // get the updated option group
2085 // if both are same return
2086 if ($currentOptionGroupId == $optionGroupId) {
2090 // check if option group is related to any other field
2091 self
::checkOptionGroup($currentOptionGroupId);
2095 * Function to check if option group is related to more than one
2098 * @params int $optionGroupId option group id
2103 static function checkOptionGroup($optionGroupId) {
2106 FROM civicrm_custom_field
2107 WHERE option_group_id = {$optionGroupId}";
2109 $count = CRM_Core_DAO
::singleValueQuery($query);
2112 //delete the option group
2113 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2117 static function getOptionGroupDefault($optionGroupId, $htmlType) {
2119 SELECT default_value, html_type
2120 FROM civicrm_custom_field
2121 WHERE option_group_id = {$optionGroupId}
2122 AND default_value IS NOT NULL
2123 ORDER BY html_type";
2125 $dao = CRM_Core_DAO
::executeQuery($query);
2126 $defaultValue = NULL;
2127 $defaultHTMLType = NULL;
2128 while ($dao->fetch()) {
2129 if ($dao->html_type
== $htmlType) {
2130 return $dao->default_value
;
2132 if ($defaultValue == NULL) {
2133 $defaultValue = $dao->default_value
;
2134 $defaultHTMLType = $dao->html_type
;
2138 // some conversions are needed if either the old or new has a html type which has potential
2139 // multiple default values.
2140 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2141 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2143 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2145 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2146 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2148 $defaultValue = substr($defaultValue, 1, -1);
2149 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2150 substr($defaultValue, 1, -1)
2152 $defaultValue = $values[0];
2155 return $defaultValue;
2158 static function postProcess(&$params,
2161 $customFieldExtends,
2164 $customData = array();
2166 foreach ($params as $key => $value) {
2167 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2169 // for autocomplete transfer hidden value instead of label
2170 if ($params[$key] && isset($params[$key . '_id'])) {
2171 $value = $params[$key . '_id'];
2174 // we need to append time with date
2175 if ($params[$key] && isset($params[$key . '_time'])) {
2176 $value .= ' ' . $params[$key . '_time'];
2179 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2182 $customFieldExtends,
2183 $customFieldInfo[1],
2192 static function buildOption($field, &$options) {
2193 // Fixme - adding anything but options to the $options array is a bad idea
2194 // What if an option had the key 'attributes'?
2195 $options['attributes'] = array(
2196 'label' => $field['label'],
2197 'data_type' => $field['data_type'],
2198 'html_type' => $field['html_type'],
2201 $optionGroupID = NULL;
2202 if (($field['html_type'] == 'CheckBox' ||
2203 $field['html_type'] == 'Radio' ||
2204 $field['html_type'] == 'Select' ||
2205 $field['html_type'] == 'AdvMulti-Select' ||
2206 $field['html_type'] == 'Multi-Select' ||
2207 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2209 if ($field['option_group_id']) {
2210 $optionGroupID = $field['option_group_id'];
2212 elseif ($field['data_type'] != 'Boolean') {
2213 CRM_Core_Error
::fatal();
2217 // build the cache for custom values with options (label => value)
2218 if ($optionGroupID != NULL) {
2221 FROM civicrm_option_value
2222 WHERE option_group_id = $optionGroupID
2225 $dao = CRM_Core_DAO
::executeQuery($query);
2226 while ($dao->fetch()) {
2227 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2228 $num = round($dao->value
, 2);
2229 $options["$num"] = $dao->label
;
2232 $options[$dao->value
] = $dao->label
;
2236 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2240 static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2241 $params = array(1 => array($fieldLabel, 'String'));
2243 $params[2] = array($groupTitle, 'String');
2246 FROM civicrm_custom_field f
2247 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2248 WHERE ( f.label = %1 OR f.name = %1 )
2249 AND ( g.title = %2 OR g.name = %2 )
2255 FROM civicrm_custom_field f
2256 WHERE ( f.label = %1 OR f.name = %1 )
2260 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2261 if ($dao->fetch() &&
2272 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2275 static function getNameFromID($ids) {
2276 if (is_array($ids)) {
2277 $ids = implode(',', $ids);
2280 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2281 FROM civicrm_custom_field f
2282 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2283 WHERE f.id IN ($ids)";
2286 $dao = CRM_Core_DAO
::executeQuery($sql);
2288 while ($dao->fetch()) {
2289 $result[$dao->id
] = array(
2290 'field_name' => $dao->field_name
,
2291 'field_label' => $dao->field_label
,
2292 'group_name' => $dao->group_name
,
2293 'group_title' => $dao->group_title
,
2300 * Validate custom data.
2302 * @param array $params custom data submitted.
2303 * ie array( 'custom_1' => 'validate me' );
2305 * @return array $errors validation errors.
2308 static function validateCustomData($params) {
2310 if (!is_array($params) ||
empty($params)) {
2315 //pick up profile fields.
2316 $profileFields = array();
2317 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2319 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2321 CRM_Core_Action
::VIEW
2325 //lets start w/ params.
2326 foreach ($params as $key => $value) {
2327 $customFieldID = self
::getKeyID($key);
2328 if (!$customFieldID) {
2332 //load the structural info for given field.
2333 $field = new CRM_Core_DAO_CustomField();
2334 $field->id
= $customFieldID;
2335 if (!$field->find(TRUE)) {
2338 $dataType = $field->data_type
;
2340 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2341 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2342 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2344 $fieldTitle = $field->label
;
2347 //no need to validate.
2348 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2352 //lets validate first for required field.
2353 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2354 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2358 //now time to take care of custom field form rules.
2359 $ruleName = $errorMsg = NULL;
2360 switch ($dataType) {
2362 $ruleName = 'integer';
2363 $errorMsg = ts('%1 must be an integer (whole number).',
2364 array(1 => $fieldTitle)
2369 $ruleName = 'money';
2370 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2371 array(1 => $fieldTitle)
2376 $ruleName = 'numeric';
2377 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2378 array(1 => $fieldTitle)
2383 $ruleName = 'wikiURL';
2384 $errorMsg = ts('%1 must be valid Website.',
2385 array(1 => $fieldTitle)
2390 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2392 $funName = "CRM_Utils_Rule::{$ruleName}";
2393 if (is_callable($funName)) {
2394 $valid = call_user_func($funName, $value);
2397 $errors[$key] = $errorMsg;
2405 static function isMultiRecordField($customId) {
2406 $isMultipleWithGid = FALSE;
2407 if (!is_numeric($customId)) {
2408 $customId = self
::getKeyID($customId);
2410 if (is_numeric($customId)) {
2411 $sql = "SELECT cg.id cgId
2412 FROM civicrm_custom_group cg
2413 INNER JOIN civicrm_custom_field cf
2414 ON cg.id = cf.custom_group_id
2415 WHERE cf.id = %1 AND cg.is_multiple = 1";
2416 $params[1] = array($customId, 'Integer');
2417 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2418 if ($dao->fetch()) {
2420 $isMultipleWithGid = $dao->cgId
;
2425 return $isMultipleWithGid;