3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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;
98 static function dataToHtml() {
99 if (!self
::$_dataToHtml) {
100 self
::$_dataToHtml = array(
102 'Text' => 'Text', 'Select' => 'Select',
103 'Radio' => 'Radio', 'CheckBox' => 'CheckBox',
104 'Multi-Select' => 'Multi-Select',
105 'AdvMulti-Select' => 'AdvMulti-Select',
106 'Autocomplete-Select' => 'Autocomplete-Select',
108 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
109 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
110 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
111 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
112 array('Date' => 'Select Date'),
113 array('Radio' => 'Radio'),
114 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
115 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
116 array('File' => 'File'),
117 array('Link' => 'Link'),
118 array('ContactReference' => 'Autocomplete-Select'),
121 return self
::$_dataToHtml;
125 * takes an associative array and creates a custom field object
127 * This function is invoked from within the web form layer and also from the api layer
129 * @param array $params (reference) an assoc array of name/value pairs
131 * @return CRM_Core_DAO_CustomField object
135 static function create(&$params) {
136 $origParams = array_merge(array(), $params);
138 if (!isset($params['id'])) {
139 if (!isset($params['column_name'])) {
140 // if add mode & column_name not present, calculate it.
141 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
143 if (!isset($params['name'])) {
144 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
148 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
153 $columnName = $params['column_name'];
156 //as during create if field is_searchable we had created index.
157 if (!empty($params['id'])) {
158 $indexExist = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
161 switch (CRM_Utils_Array
::value('html_type', $params)){
163 if(empty($params['date_format'])){
164 $config = CRM_Core_Config
::singleton();
165 $params['date_format'] = $config->dateInputFormat
;
169 case 'AdvMulti-Select':
171 if (isset($params['default_checkbox_option'])) {
172 $tempArray = array_keys($params['default_checkbox_option']);
173 $defaultArray = array();
174 foreach ($tempArray as $k => $v) {
175 if ($params['option_value'][$v]) {
176 $defaultArray[] = $params['option_value'][$v];
180 if (!empty($defaultArray)) {
181 // also add the seperator before and after the value per new conventio (CRM-1604)
182 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
186 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
188 $params['default_value'] = $params['option_value'][$params['default_option']];
194 $transaction = new CRM_Core_Transaction();
195 // create any option group & values if required
196 if ($params['html_type'] != 'Text' &&
197 in_array($params['data_type'], array(
198 'String', 'Int', 'Float', 'Money'))
201 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
202 $params['custom_group_id'],
207 if ($params['option_type'] == 1) {
208 // first create an option group for this custom group
209 $optionGroup = new CRM_Core_DAO_OptionGroup();
210 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
211 $optionGroup->title
= $params['label'];
212 $optionGroup->is_active
= 1;
213 $optionGroup->save();
214 $params['option_group_id'] = $optionGroup->id
;
215 if(!empty($params['option_value']) && is_array($params['option_value'])){
216 foreach ($params['option_value'] as $k => $v) {
217 if (strlen(trim($v))) {
218 $optionValue = new CRM_Core_DAO_OptionValue();
219 $optionValue->option_group_id
= $optionGroup->id
;
220 $optionValue->label
= $params['option_label'][$k];
221 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$k]);
222 switch ($params['data_type']) {
224 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($v);
228 $optionValue->value
= intval($v);
232 $optionValue->value
= floatval($v);
236 $optionValue->value
= trim($v);
239 $optionValue->weight
= $params['option_weight'][$k];
240 $optionValue->is_active
= CRM_Utils_Array
::value($k, $params['option_status'], FALSE);
241 $optionValue->save();
248 // check for orphan option groups
249 if (!empty($params['option_group_id'])) {
250 if (!empty($params['id'])) {
251 self
::fixOptionGroups($params['id'], $params['option_group_id']);
254 // if we dont have a default value
255 // retrive it from one of the other custom fields which use this option group
256 if (empty($params['default_value'])) {
257 //don't insert only value separator as default value, CRM-4579
258 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
262 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
265 $params['default_value'] = $defaultValue;
270 // since we need to save option group id :)
271 if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
272 $params['attributes'] = 'rows=4, cols=60';
275 $customField = new CRM_Core_DAO_CustomField();
276 $customField->copyValues($params);
277 $customField->is_required
= CRM_Utils_Array
::value('is_required', $params, FALSE);
278 $customField->is_searchable
= CRM_Utils_Array
::value('is_searchable', $params, FALSE);
279 $customField->in_selector
= CRM_Utils_Array
::value('in_selector', $params, FALSE);
280 $customField->is_search_range
= CRM_Utils_Array
::value('is_search_range', $params, FALSE);
281 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, FALSE);
282 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
283 $customField->save();
285 // make sure all values are present in the object for further processing
286 $customField->find(TRUE);
288 //create/drop the index when we toggle the is_searchable flag
289 if (!empty($params['id'])) {
290 self
::createField($customField, 'modify', $indexExist);
293 if (!isset($origParams['column_name'])) {
294 $columnName .= "_{$customField->id}";
295 $params['column_name'] = $columnName;
297 $customField->column_name
= $columnName;
298 $customField->save();
299 // make sure all values are present in the object
300 $customField->find(TRUE);
302 self
::createField($customField, 'add');
305 // complete transaction
306 $transaction->commit();
308 CRM_Utils_System
::flushCache();
314 * Takes a bunch of params that are needed to match certain criteria and
315 * retrieves the relevant objects. Typically the valid params are only
316 * contact_id. We'll tweak this function to be more full featured over a period
317 * of time. This is the inverse function of create. It also stores all the retrieved
318 * values in the default array
320 * @param array $params (reference ) an assoc array of name/value pairs
321 * @param array $defaults (reference ) an assoc array to hold the flattened values
323 * @return object CRM_Core_DAO_CustomField object
327 static function retrieve(&$params, &$defaults) {
328 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
332 * update the is_active flag in the db
334 * @param int $id Id of the database record
335 * @param boolean $is_active Value we want to set the is_active field
337 * @return Object DAO object on sucess, null otherwise
342 static function setIsActive($id, $is_active) {
344 CRM_Utils_System
::flushCache();
346 //enable-disable CustomField
347 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
348 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
352 * Get the field title.
354 * @param int $id id of field.
356 * @return string name
362 public static function getTitle($id) {
363 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
367 * Store and return an array of all active custom fields.
369 * @param string $customDataType type of Custom Data; empty is a synonym for "all contact data types"
370 * @param boolean $showAll If true returns all fields (includes disabled fields)
371 * @param boolean $inline If true returns all inline fields (includes disabled fields)
372 * @param int $customDataSubType Custom Data sub type value
373 * @param int $customDataSubName Custom Data sub name value
374 * @param boolean $onlyParent return only top level custom data, for eg, only Participant and ignore subname and subtype
375 * @param boolean $onlySubType return only custom data for subtype
376 * @param boolean $checkPermission if false, do not include permissioning clause
378 * @return array $fields - an array of active custom fields.
383 public static function &getFields($customDataType = 'Individual',
386 $customDataSubType = NULL,
387 $customDataSubName = NULL,
389 $onlySubType = FALSE,
390 $checkPermission = TRUE
392 if (empty($customDataType)) {
393 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
395 if ($customDataType && !is_array($customDataType)) {
397 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
398 // This is the case when getFieldsForImport() requires fields
399 // limited strictly to a subtype.
400 $customDataSubType = $customDataType;
401 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
405 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
406 // this makes the method flexible to support retrieving fields
407 // for multiple extends value.
408 $customDataType = array($customDataType);
412 if ($customDataSubType && !is_array($customDataSubType)) {
413 $customDataSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
414 trim($customDataSubType, CRM_Core_DAO
::VALUE_SEPARATOR
)
418 if (is_array($customDataType)) {
419 $cacheKey = implode('_', $customDataType);
422 $cacheKey = $customDataType;
425 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
426 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
427 $cacheKey .= $showAll ?
'_1' : '_0';
428 $cacheKey .= $inline ?
'_1_' : '_0_';
429 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
430 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
431 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
433 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
435 // also get the permission stuff here
436 if ($checkPermission) {
437 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
442 $permissionClause = '(1)';
445 // lets md5 permission clause and take first 8 characters
446 $cacheKey .= substr(md5($permissionClause), 0, 8);
448 if (strlen($cacheKey) > 40) {
449 $cacheKey = md5($cacheKey);
452 if (!self
::$_importFields ||
453 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
455 if (!self
::$_importFields) {
456 self
::$_importFields = array();
459 // check if we can retrieve from database cache
460 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
462 if ($fields === NULL) {
463 $cfTable = self
::getTableName();
466 if (is_array($customDataType)) {
468 foreach ($customDataType as $dataType) {
469 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
470 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
471 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
474 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
476 $value = $value ?
$value . ", {$val}" : $val;
480 $extends = "AND $cgTable.extends IN ( $value ) ";
484 if (!empty($customDataType) && empty($extends)) {
485 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
486 self
::$_importFields[$cacheKey] = array();
487 return self
::$_importFields[$cacheKey];
491 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
494 $query = "SELECT $cfTable.id, $cfTable.label,
498 $cfTable.default_value,
499 $cfTable.options_per_line, $cfTable.text_length,
500 $cfTable.custom_group_id,
501 $cgTable.extends, $cfTable.is_search_range,
502 $cgTable.extends_entity_column_value,
503 $cgTable.extends_entity_column_id,
505 $cfTable.option_group_id,
506 $cfTable.date_format,
507 $cfTable.time_format,
511 ON $cfTable.custom_group_id = $cgTable.id
515 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
519 $query .= " AND $cgTable.style = 'Inline' ";
522 //get the custom fields for specific type in
523 //combination with fields those support any type.
524 if (!empty($customDataSubType)) {
525 $subtypeClause = array();
526 foreach ($customDataSubType as $subtype) {
527 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
528 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
531 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
533 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
536 if ($customDataSubName) {
537 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
540 // also get the permission stuff here
541 if ($checkPermission) {
542 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
547 $permissionClause = '(1)';
550 $query .= " $extends AND $permissionClause
551 ORDER BY $cgTable.weight, $cgTable.title,
552 $cfTable.weight, $cfTable.label";
554 $dao = CRM_Core_DAO
::executeQuery($query);
557 while (($dao->fetch()) != NULL) {
558 $fields[$dao->id
]['label'] = $dao->label
;
559 $fields[$dao->id
]['groupTitle'] = $dao->title
;
560 $fields[$dao->id
]['data_type'] = $dao->data_type
;
561 $fields[$dao->id
]['html_type'] = $dao->html_type
;
562 $fields[$dao->id
]['default_value'] = $dao->default_value
;
563 $fields[$dao->id
]['text_length'] = $dao->text_length
;
564 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
565 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
566 $fields[$dao->id
]['extends'] = $dao->extends;
567 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
568 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
569 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
570 $fields[$dao->id
]['is_view'] = $dao->is_view
;
571 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
572 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
573 $fields[$dao->id
]['date_format'] = $dao->date_format
;
574 $fields[$dao->id
]['time_format'] = $dao->time_format
;
577 CRM_Core_BAO_Cache
::setItem($fields,
579 "custom importableFields $cacheKey"
582 self
::$_importFields[$cacheKey] = $fields;
585 return self
::$_importFields[$cacheKey];
589 * Return the field ids and names (with groups) for import purpose.
591 * @param int|string $contactType Contact type
592 * @param boolean $showAll If true returns all fields (includes disabled fields)
593 * @param boolean $onlyParent return fields ONLY related to basic types
594 * @param boolean $search when called from search and multiple records need to be returned
595 * @param boolean $checkPermission if false, do not include permissioning clause
597 * @param bool $withMultiple
599 * @return array $fields -
604 public static function &getFieldsForImport($contactType = 'Individual',
608 $checkPermission = TRUE,
609 $withMultiple = FALSE
611 // Note: there are situations when we want getFieldsForImport() return fields related
612 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
613 $fields = &self
::getFields($contactType,
623 $importableFields = array();
624 foreach ($fields as $id => $values) {
625 // for now we should not allow multiple fields in profile / export etc, hence unsetting
627 (!empty($values['is_multiple']) && !$withMultiple)
632 /* generate the key for the fields array */
636 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
637 $importableFields[$key] = array(
639 'title' => CRM_Utils_Array
::value('label', $values),
640 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
642 'custom_field_id' => $id,
643 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
644 'data_type' => CRM_Utils_Array
::value('data_type', $values),
645 'html_type' => CRM_Utils_Array
::value('html_type', $values),
646 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
649 // CRM-6681, pass date and time format when html_type = Select Date
650 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
651 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
652 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
656 return $importableFields;
660 * Get the field id from an import key
662 * @param string $key The key to parse
665 * @return int|null The id (if exists)
669 public static function getKeyID($key, $all = FALSE) {
671 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
678 CRM_Utils_Array
::value(2, $match),
687 * Use the cache to get all values of a specific custom field
689 * @param int $fieldID the custom field ID
691 * @return CRM_Core_DAO_CustomField $field the field object
695 static function getFieldObject($fieldID) {
696 $field = new CRM_Core_DAO_CustomField();
698 // check if we can get the field values from the system cache
699 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
700 $cache = CRM_Utils_Cache
::singleton();
701 $fieldValues = $cache->get($cacheKey);
702 if (empty($fieldValues)) {
703 $field->id
= $fieldID;
704 if (!$field->find(TRUE)) {
705 CRM_Core_Error
::fatal();
708 $fieldValues = array();
709 CRM_Core_DAO
::storeValues($field, $fieldValues);
711 $cache->set($cacheKey, $fieldValues);
714 $field->copyValues($fieldValues);
721 * This function for building custom fields
723 * @param CRM_Core_Form $qf form object (reference)
724 * @param string $elementName name of the custom field
726 * @param boolean $inactiveNeeded
727 * @param bool $useRequired
728 * @param boolean $search true if used for search else false
729 * @param string $label label for custom field
731 * @internal param bool $userRequired true if required else false
735 public static function addQuickFormElement(&$qf,
738 $inactiveNeeded = FALSE,
743 $field = self
::getFieldObject($fieldId);
745 // Custom field HTML should indicate group+field name
746 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
747 $dataCrmCustomVal = $groupName.':'.$field->name
;
748 $dataCrmCustomAttr = 'data-crm-custom="'.$dataCrmCustomVal.'"';
749 $field->attributes
.= $dataCrmCustomAttr;
751 // Fixed for Issue CRM-2183
752 if ($field->html_type
== 'TextArea' && $search) {
753 $field->html_type
= 'Text';
756 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
758 // FIXME: Why are select state/country separate widget types?
759 if (in_array($field->html_type
, array('Select', 'Multi-Select', 'Select State/Province', 'Multi-Select State/Province', 'Select Country', 'Multi-Select Country'))) {
760 $selectAttributes = array(
761 'data-crm-custom' => $dataCrmCustomVal,
762 'class' => 'crm-select2',
764 if (strpos($field->html_type
, 'Multi') === 0) {
765 $selectAttributes['multiple'] = 'multiple';
768 // Add data so popup link. Normally this is handled by CRM_Core_Form->addSelect
769 if ($field->option_group_id
&& !$search && in_array($field->html_type
, array('Select', 'Multi-Select')) && CRM_Core_Permission
::check('administer CiviCRM')) {
770 $selectAttributes +
= array(
771 'data-api-entity' => 'contact', // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
772 'data-api-field' => 'custom_' . $field->id
,
773 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
777 if (!isset($label)) {
778 $label = $field->label
;
782 * at some point in time we might want to split the below into small functions
785 switch ($field->html_type
) {
787 if ($field->is_search_range
&& $search) {
788 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
789 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
792 $element = &$qf->add(strtolower($field->html_type
), $elementName, $label,
794 $useRequired && !$search
800 $attributes = $dataCrmCustomAttr;
801 if ($field->note_rows
) {
802 $attributes .= 'rows=' . $field->note_rows
;
805 $attributes .= 'rows=4';
807 if ($field->note_columns
) {
808 $attributes .= ' cols=' . $field->note_columns
;
811 $attributes .= ' cols=60';
813 if ($field->text_length
) {
814 $attributes .= ' maxlength=' . $field->text_length
;
816 $element = &$qf->add(strtolower($field->html_type
),
820 $useRequired && !$search
825 if ($field->is_search_range
&& $search) {
826 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
828 'format' => $field->date_format
,
829 'timeFormat' => $field->time_format
,
830 'startOffset' => $field->start_date_years
,
831 'endOffset' => $field->end_date_years
,
832 'data-crm-custom' => $dataCrmCustomVal,
836 $qf->addDate($elementName . '_to', ts('To'), FALSE,
838 'format' => $field->date_format
,
839 'timeFormat' => $field->time_format
,
840 'startOffset' => $field->start_date_years
,
841 'endOffset' => $field->end_date_years
,
842 'data-crm-custom' => $dataCrmCustomVal,
847 $required = $useRequired && !$search;
849 $qf->addDate($elementName, $label, $required, array(
850 'format' => $field->date_format
,
851 'timeFormat' => $field->time_format
,
852 'startOffset' => $field->start_date_years
,
853 'endOffset' => $field->end_date_years
,
854 'data-crm-custom' => $dataCrmCustomVal,
861 if ($field->data_type
!= 'Boolean') {
862 $customOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
863 $field->option_group_id
865 foreach ($customOption as $v => $l) {
866 $choice[] = $qf->createElement('radio', NULL, '', $l, (string)$v, $field->attributes
);
868 $group = $qf->addGroup($choice, $elementName, $label);
871 $choice[] = $qf->createElement('radio', NULL, '', ts('Yes'), '1', $field->attributes
);
872 $choice[] = $qf->createElement('radio', NULL, '', ts('No'), '0', $field->attributes
);
873 $group = $qf->addGroup($choice, $elementName, $label);
875 if ($useRequired && !$search) {
876 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
879 $group->setAttribute('allowClear', TRUE);
884 $selectOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
885 $field->option_group_id
888 $qf->add('select', $elementName, $label,
889 array('' => $placeholder) +
$selectOption,
890 $useRequired && !$search,
895 //added for select multiple
897 case 'AdvMulti-Select':
898 $selectOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
899 $field->option_group_id
902 count($selectOption) > 1
904 $selectOption['CiviCRM_OP_OR'] = ts('Select to match ANY; unselect to match ALL');
907 $include =& $qf->addElement(
910 $label, $selectOption,
914 'class' => 'advmultiselect',
915 'data-crm-custom' => $dataCrmCustomVal,
919 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
920 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
922 if ($useRequired && !$search) {
923 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
928 $selectOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
929 $field->option_group_id
932 count($selectOption) > 1
934 $selectOption['CiviCRM_OP_OR'] = ts('Select to match ANY; unselect to match ALL');
936 $qf->addElement('select', $elementName, $label, $selectOption, $selectAttributes);
938 if ($useRequired && !$search) {
939 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
944 $customOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
945 $field->option_group_id
948 foreach ($customOption as $v => $l) {
949 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
954 $check[] = &$qf->addElement('advcheckbox', 'CiviCRM_OP_OR', NULL, ts('Check to match ANY; uncheck to match ALL'), array('data-crm-custom' => $dataCrmCustomVal));
956 $qf->addGroup($check, $elementName, $label);
957 if ($useRequired && !$search) {
958 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
963 // we should not build upload file in search mode
968 strtolower($field->html_type
),
972 $useRequired && !$search
974 $qf->addUploadElement($elementName);
977 case 'Select State/Province':
979 $stateOption = array('' => $placeholder) + CRM_Core_PseudoConstant
::stateProvince();
980 $qf->add('select', $elementName, $label, $stateOption,
981 $useRequired && !$search,
984 $qf->_stateCountryMap
['state_province'][] = $elementName;
987 case 'Multi-Select State/Province':
988 //Add Multi-select State/Province
989 $stateOption = CRM_Core_PseudoConstant
::stateProvince();
991 $qf->addElement('select', $elementName, $label, $stateOption, $selectAttributes);
992 if ($useRequired && !$search) {
993 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
997 case 'Select Country':
999 $countryOption = array('' => $placeholder) + CRM_Core_PseudoConstant
::country();
1000 $qf->add('select', $elementName, $label, $countryOption,
1001 $useRequired && !$search,
1004 $qf->_stateCountryMap
['country'][] = $elementName;
1007 case 'Multi-Select Country':
1009 $countryOption = CRM_Core_PseudoConstant
::country();
1010 $qf->addElement('select', $elementName, $label, $countryOption, $selectAttributes);
1011 if ($useRequired && !$search) {
1012 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
1016 case 'RichTextEditor':
1017 $attributes = array('rows' => $field->note_rows
, 'cols' => $field->note_columns
, 'data-crm-custom' => $dataCrmCustomVal);
1018 if ($field->text_length
) {
1019 $attributes['maxlength'] = $field->text_length
;
1021 $qf->addWysiwyg($elementName, $label, $attributes, $search);
1024 case 'Autocomplete-Select':
1025 static $customUrls = array();
1026 // Fixme: why is this a string in the first place??
1027 $attributes = array();
1028 if ($field->attributes
) {
1029 foreach(explode(' ', $field->attributes
) as $at) {
1030 if (strpos($at, '=')) {
1031 list($k, $v) = explode('=', $at);
1032 $attributes[$k] = trim($v, ' "');
1036 if ($field->data_type
== 'ContactReference') {
1037 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1038 $attributes['data-api-entity'] = 'contact';
1039 $qf->add('text', $elementName, $label, $attributes,
1040 $useRequired && !$search
1043 $urlParams = "context=customfield&id={$field->id}";
1045 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1052 // FIXME: This won't work with customFieldOptions hook
1053 $attributes +
= array(
1054 'entity' => 'option_value',
1055 'placeholder' => $placeholder,
1057 'params' => array('option_group_id' => $field->option_group_id
),
1060 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1063 $qf->assign('customUrls', $customUrls);
1067 switch ($field->data_type
) {
1069 // integers will have numeric rule applied to them.
1070 if ($field->is_search_range
&& $search) {
1071 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1072 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1075 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1080 if ($field->is_search_range
&& $search) {
1081 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1082 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1085 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1090 if ($field->is_search_range
&& $search) {
1091 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1092 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1095 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1105 'onfocus' => "if (!this.value) { this.value='http://';} else return false",
1106 'onblur' => "if ( this.value == 'http://') { this.value='';} else return false",
1107 'data-crm-custom' => $dataCrmCustomVal,
1109 $useRequired && !$search
1111 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1114 if ($field->is_view
&& !$search) {
1115 $qf->freeze($elementName);
1120 * Delete the Custom Field.
1122 * @param object $field - the field object
1130 public static function deleteField($field) {
1131 CRM_Utils_System
::flushCache();
1133 // first delete the custom option group and values associated with this field
1134 if ($field->option_group_id
) {
1135 //check if option group is related to any other field, if
1136 //not delete the option group and related option values
1137 self
::checkOptionGroup($field->option_group_id
);
1140 // next drop the column from the custom value table
1141 self
::createField($field, 'delete');
1144 CRM_Core_BAO_UFField
::delUFField($field->id
);
1145 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1151 * Given a custom field value, its id and the set of options
1152 * find the display value for this field
1154 * @param mixed $value the custom field value
1155 * @param int $id the custom field id
1156 * @param int $options the assoc array of option name/value pairs
1158 * @param null $contactID
1159 * @param null $fieldID
1161 * @return string the display value
1166 static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1167 $option = &$options[$id];
1168 $attributes = &$option['attributes'];
1169 $html_type = $attributes['html_type'];
1170 $data_type = $attributes['data_type'];
1171 $format = CRM_Utils_Array
::value('format', $attributes);
1173 return self
::getDisplayValueCommon($value,
1188 * @param null $format
1189 * @param null $contactID
1190 * @param null $fieldID
1192 * @return array|mixed|null|string
1194 static function getDisplayValueCommon($value,
1205 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1206 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1207 $html_type == 'Select' ||
1208 $html_type == 'CheckBox' ||
1209 $html_type == 'AdvMulti-Select' ||
1210 $html_type == 'Multi-Select'
1213 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1216 switch ($html_type) {
1218 if ($data_type == 'Boolean') {
1219 // Do not assume that if not yes means no.
1222 $display = ts('Yes');
1224 elseif ((string)$value === '0') {
1225 $display = ts('No');
1229 $display = CRM_Utils_Array
::value($value, $option);
1233 case 'Autocomplete-Select':
1234 if ($data_type == 'ContactReference' &&
1237 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1240 $display = CRM_Utils_Array
::value($value, $option);
1245 $display = CRM_Utils_Array
::value($value, $option);
1249 case 'AdvMulti-Select':
1250 case 'Multi-Select':
1251 if (is_array($value)) {
1252 $checkedData = $value;
1255 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1256 substr($value, 1, -1)
1258 if ($html_type == 'CheckBox') {
1260 foreach ($checkedData as $v) {
1263 $checkedData = $newData;
1269 foreach ($checkedData as $key => $val) {
1270 if ($key === 'CiviCRM_OP_OR') {
1274 if ($html_type == 'CheckBox') {
1277 $v[] = CRM_Utils_Array
::value($key, $option);
1282 $v[] = CRM_Utils_Array
::value($val, $option);
1286 $display = implode(', ', $v);
1291 if (is_array($value)) {
1292 foreach ($value as $key => $val) {
1293 $display[$key] = CRM_Utils_Date
::customFormat($val);
1297 // remove time element display if time is not set
1298 if (empty($option['attributes']['time_format'])) {
1299 $value = substr($value, 0, 10);
1301 $display = CRM_Utils_Date
::customFormat($value);
1305 case 'Select State/Province':
1306 if (empty($value)) {
1310 $display = CRM_Core_PseudoConstant
::stateProvince($value);
1314 case 'Multi-Select State/Province':
1315 if (is_array($value)) {
1316 $checkedData = $value;
1319 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1320 substr($value, 1, -1)
1324 $states = CRM_Core_PseudoConstant
::stateProvince();
1326 foreach ($checkedData as $stateID) {
1330 $display .= $states[$stateID];
1334 case 'Select Country':
1335 if (empty($value)) {
1339 $display = CRM_Core_PseudoConstant
::country($value);
1343 case 'Multi-Select Country':
1344 if (is_array($value)) {
1345 $checkedData = $value;
1348 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1349 substr($value, 1, -1)
1353 $countries = CRM_Core_PseudoConstant
::country();
1355 foreach ($checkedData as $countryID) {
1359 $display .= $countries[$countryID];
1365 $url = self
::getFileURL($contactID, $fieldID, $value);
1367 $display = $url['file_url'];
1373 if (empty($value)) {
1377 $display = nl2br($value);
1382 if (empty($value)) {
1389 return $display ?
$display : $value;
1393 * Function to set default values for custom data used in profile
1395 * @params int $customFieldId custom field id
1396 * @params string $elementName custom field name
1397 * @params array $defaults associated array of fields
1398 * @params int $contactId contact id
1399 * @param $customFieldId
1400 * @param $elementName
1402 * @param null $contactId
1403 * @param int $mode profile mode
1404 * @param mixed $value if passed - dont fetch value from db,
1405 * just format the given value
1410 static function setProfileDefaults($customFieldId,
1417 //get the type of custom field
1418 $customField = new CRM_Core_BAO_CustomField();
1419 $customField->id
= $customFieldId;
1420 $customField->find(TRUE);
1423 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1424 $value = $customField->default_value
;
1428 if (!isset($value)) {
1429 $info = self
::getTableColumnGroup($customFieldId);
1430 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1431 $result = CRM_Core_DAO
::executeQuery($query);
1432 if ($result->fetch()) {
1433 $value = $result->value
;
1437 if ($customField->data_type
== 'Country') {
1439 $config = CRM_Core_Config
::singleton();
1440 if ($config->defaultContactCountry
) {
1441 $value = $config->defaultContactCountry();
1447 //set defaults if mode is registration
1448 if (!trim($value) &&
1450 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1452 $value = $customField->default_value
;
1455 if ($customField->data_type
== 'Money' && isset($value)) {
1456 $value = number_format($value, 2);
1458 switch ($customField->html_type
) {
1460 case 'AdvMulti-Select':
1461 case 'Multi-Select':
1462 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1463 $defaults[$elementName] = array();
1464 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1465 substr($value, 1, -1)
1467 foreach ($customOption as $val) {
1468 if (in_array($val['value'], $checkedValue)) {
1469 if ($customField->html_type
== 'CheckBox') {
1470 $defaults[$elementName][$val['value']] = 1;
1472 elseif ($customField->html_type
== 'Multi-Select' ||
1473 $customField->html_type
== 'AdvMulti-Select'
1475 $defaults[$elementName][$val['value']] = $val['value'];
1483 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1486 $customField->date_format
,
1487 $customField->time_format
1492 case 'Autocomplete-Select':
1493 if ($customField->data_type
== 'ContactReference') {
1494 if (is_numeric($value)) {
1495 $defaults[$elementName . '_id'] = $value;
1496 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1500 $defaults[$elementName] = $value;
1505 $defaults[$elementName] = $value;
1512 * @param null $fileID
1513 * @param bool $absolute
1520 * @param null $fileID
1521 * @param bool $absolute
1525 static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE) {
1528 $params = array('id' => $cfID);
1529 $defaults = array();
1530 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1531 $columnName = $defaults['column_name'];
1533 //table name of custom data
1534 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1535 $defaults['custom_group_id'],
1539 //query to fetch id from civicrm_file
1540 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1541 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1546 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1551 $result['file_id'] = $fileID;
1553 if ($fileType == 'image/jpeg' ||
1554 $fileType == 'image/pjpeg' ||
1555 $fileType == 'image/gif' ||
1556 $fileType == 'image/x-png' ||
1557 $fileType == 'image/png'
1559 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1564 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1565 list($imageWidth, $imageHeight) = getimagesize($path);
1566 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1567 $url = CRM_Utils_System
::url('civicrm/file',
1568 "reset=1&id=$fileID&eid=$contactID",
1569 $absolute, NULL, TRUE, TRUE
1571 $result['file_url'] = "
1572 <a href=\"$url\" class='crm-image-popup'>
1573 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1575 // for non image files
1578 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1582 $url = CRM_Utils_System
::url('civicrm/file',
1583 "reset=1&id=$fileID&eid=$contactID",
1584 $absolute, NULL, TRUE, TRUE
1586 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1594 * Format custom fields before inserting
1596 * @param int $customFieldId custom field id
1597 * @param array $customFormatted formatted array
1598 * @param mix $value value of custom field
1599 * @param string $customFieldExtend custom field extends
1600 * @param int $customValueId custom option value id
1601 * @param int $entityId entity id (contribution, membership...)
1602 * @param boolean $inline consider inline custom groups only
1603 * @param boolean $checkPermission if false, do not include permissioning clause
1605 * @return array $customFormatted formatted custom field array
1608 static function formatCustomField($customFieldId, &$customFormatted, $value,
1609 $customFieldExtend, $customValueId = NULL,
1612 $checkPermission = TRUE
1614 //get the custom fields for the entity
1615 //subtype and basic type
1616 $customDataSubType = NULL;
1617 if (is_array($customFieldExtend)) {
1618 $customFieldExtend = $customFieldExtend[0];
1621 if (in_array($customFieldExtend,
1622 CRM_Contact_BAO_ContactType
::subTypes()
1624 // This is the case when getFieldsForImport() requires fields
1625 // of subtype and its parent.CRM-5143
1626 $customDataSubType = $customFieldExtend;
1627 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1630 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1640 if (!array_key_exists($customFieldId, $customFields)) {
1644 // return if field is a 'code' field
1645 if (!empty($customFields[$customFieldId]['is_view'])) {
1649 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1651 if (!$customValueId &&
1652 // we always create new entites for is_multiple unless specified
1653 !$customFields[$customFieldId]['is_multiple'] &&
1659 WHERE entity_id={$entityId}";
1661 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1664 //fix checkbox, now check box always submits values
1665 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1667 // Note that only during merge this is not an array, and you can directly use value
1668 if (is_array($value)) {
1669 $selectedValues = array();
1670 foreach ($value as $selId => $val) {
1672 $selectedValues[] = $selId;
1675 if (!empty($selectedValues)) {
1676 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1678 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1687 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1688 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1691 // Note that only during merge this is not an array,
1692 // and you can directly use value, CRM-4385
1693 if (is_array($value)) {
1694 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1695 array_values($value)
1696 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1704 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1705 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1706 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1708 $customFields[$customFieldId]['data_type'] == 'String' &&
1709 !empty($customFields[$customFieldId]['text_length']) &&
1712 // lets make sure that value is less than the length, else we'll
1713 // be losing some data, CRM-7481
1714 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1715 // need to do a few things here
1717 // 1. lets find a new length
1718 $newLength = $customFields[$customFieldId]['text_length'];
1719 $minLength = strlen($value);
1720 while ($newLength < $minLength) {
1721 $newLength = $newLength * 2;
1724 // set the custom field meta data to have a length larger than value
1725 // alter the custom value table column to match this length
1726 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1731 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1732 if (!CRM_Utils_System
::isNull($value)) {
1733 $format = $customFields[$customFieldId]['date_format'];
1734 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1739 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1740 $customFields[$customFieldId]['data_type'] == 'Money'
1746 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1747 $value = CRM_Utils_Rule
::cleanMoney($value);
1751 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1752 $customFields[$customFieldId]['data_type'] == 'Country'
1762 if ($customFields[$customFieldId]['data_type'] == 'File') {
1763 if (empty($value)) {
1767 $config = CRM_Core_Config
::singleton();
1769 $fName = $value['name'];
1770 $mimeType = $value['type'];
1772 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1774 // rename this file to go into the secure directory
1775 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1776 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1779 if ($customValueId) {
1784 $params = array(1 => array($customValueId, 'Integer'));
1785 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1788 $fileDAO = new CRM_Core_DAO_File();
1791 $fileDAO->id
= $fileId;
1794 $fileDAO->uri
= $filename;
1795 $fileDAO->mime_type
= $mimeType;
1796 $fileDAO->upload_date
= date('Ymdhis');
1798 $fileId = $fileDAO->id
;
1802 if (!is_array($customFormatted)) {
1803 $customFormatted = array();
1806 if (!array_key_exists($customFieldId, $customFormatted)) {
1807 $customFormatted[$customFieldId] = array();
1811 if ($customValueId) {
1812 $index = $customValueId;
1815 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1816 $customFormatted[$customFieldId][$index] = array();
1818 $customFormatted[$customFieldId][$index] = array(
1819 'id' => $customValueId > 0 ?
$customValueId : NULL,
1821 'type' => $customFields[$customFieldId]['data_type'],
1822 'custom_field_id' => $customFieldId,
1823 'custom_group_id' => $groupID,
1824 'table_name' => $tableName,
1825 'column_name' => $columnName,
1826 'file_id' => $fileId,
1827 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1830 //we need to sort so that custom fields are created in the order of entry
1831 krsort($customFormatted[$customFieldId]);
1832 return $customFormatted;
1840 static function &defaultCustomTableSchema(&$params) {
1841 // add the id and extends_id
1843 'name' => $params['name'],
1844 'is_multiple' => $params['is_multiple'],
1845 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1849 'type' => 'int unsigned',
1852 'attributes' => 'AUTO_INCREMENT',
1853 'comment' => 'Default MySQL primary key',
1856 'name' => 'entity_id',
1857 'type' => 'int unsigned',
1859 'comment' => 'Table that this extends',
1860 'fk_table_name' => $params['extends_name'],
1861 'fk_field_name' => 'id',
1862 'fk_attributes' => 'ON DELETE CASCADE',
1867 if (!$params['is_multiple']) {
1868 $table['indexes'] = array(
1871 'field_name_1' => 'entity_id',
1881 * @param bool $indexExist
1882 * @param bool $triggerRebuild
1884 static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1885 $tableName = CRM_Core_DAO
::getFieldValue(
1886 'CRM_Core_DAO_CustomGroup',
1887 $field->custom_group_id
,
1892 'table_name' => $tableName,
1893 'operation' => $operation,
1894 'name' => $field->column_name
,
1895 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1899 'required' => $field->is_required
,
1900 'searchable' => $field->is_searchable
,
1903 if ($operation == 'delete') {
1904 $fkName = "{$tableName}_{$field->column_name}";
1905 if (strlen($fkName) >= 48) {
1906 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1908 $params['fkName'] = $fkName;
1910 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1911 $params['fk_table_name'] = 'civicrm_country';
1912 $params['fk_field_name'] = 'id';
1913 $params['fk_attributes'] = 'ON DELETE SET NULL';
1915 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1916 $params['type'] = 'varchar(255)';
1918 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1919 $params['fk_table_name'] = 'civicrm_state_province';
1920 $params['fk_field_name'] = 'id';
1921 $params['fk_attributes'] = 'ON DELETE SET NULL';
1923 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1924 $params['type'] = 'varchar(255)';
1926 elseif ($field->data_type
== 'File') {
1927 $params['fk_table_name'] = 'civicrm_file';
1928 $params['fk_field_name'] = 'id';
1929 $params['fk_attributes'] = 'ON DELETE SET NULL';
1931 elseif ($field->data_type
== 'ContactReference') {
1932 $params['fk_table_name'] = 'civicrm_contact';
1933 $params['fk_field_name'] = 'id';
1934 $params['fk_attributes'] = 'ON DELETE SET NULL';
1936 if ($field->default_value
) {
1937 $params['default'] = "'{$field->default_value}'";
1940 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1944 * Determine whether it would be safe to move a field
1946 * @param int $fieldID FK to civicrm_custom_field
1947 * @param int $newGroupID FK to civicrm_custom_group
1952 static function _moveFieldValidate($fieldID, $newGroupID) {
1955 $field = new CRM_Core_DAO_CustomField();
1956 $field->id
= $fieldID;
1957 if (!$field->find(TRUE)) {
1958 $errors['fieldID'] = 'Invalid ID for custom field';
1962 $oldGroup = new CRM_Core_DAO_CustomGroup();
1963 $oldGroup->id
= $field->custom_group_id
;
1964 if (!$oldGroup->find(TRUE)) {
1965 $errors['fieldID'] = 'Invalid ID for old custom group';
1969 $newGroup = new CRM_Core_DAO_CustomGroup();
1970 $newGroup->id
= $newGroupID;
1971 if (!$newGroup->find(TRUE)) {
1972 $errors['newGroupID'] = 'Invalid ID for new custom group';
1978 FROM civicrm_custom_field a
1979 INNER JOIN civicrm_custom_field b
1981 AND a.label = b.label
1982 AND b.custom_group_id = %2
1985 1 => array($field->id
, 'Integer'),
1986 2 => array($newGroup->id
, 'Integer'),
1988 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1990 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1993 $tableName = $oldGroup->table_name
;
1994 $columnName = $field->column_name
;
1999 WHERE $columnName is not null
2001 $count = CRM_Core_DAO
::singleValueQuery($query,
2002 CRM_Core_DAO
::$_nullArray
2007 FROM civicrm_custom_group
2008 WHERE id IN ( %1, %2 )
2010 $params = array(1 => array($oldGroup->id
, 'Integer'),
2011 2 => array($newGroup->id
, 'Integer'),
2014 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2016 while ($dao->fetch()) {
2017 $extends[] = $dao->extends;
2019 if ($extends[0] != $extends[1]) {
2020 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
2024 return empty($errors) ?
TRUE : $errors;
2028 * Move a custom data field from one group (table) to another
2030 * @param int $fieldID FK to civicrm_custom_field
2031 * @param int $newGroupID FK to civicrm_custom_group
2035 static function moveField($fieldID, $newGroupID) {
2036 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
2037 if (TRUE !== $validation) {
2038 CRM_Core_Error
::fatal(implode(' ', $validation));
2040 $field = new CRM_Core_DAO_CustomField();
2041 $field->id
= $fieldID;
2044 $newGroup = new CRM_Core_DAO_CustomGroup();
2045 $newGroup->id
= $newGroupID;
2046 $newGroup->find(TRUE);
2048 $oldGroup = new CRM_Core_DAO_CustomGroup();
2049 $oldGroup->id
= $field->custom_group_id
;
2050 $oldGroup->find(TRUE);
2053 $add->custom_group_id
= $newGroup->id
;
2054 self
::createField($add, 'add');
2056 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
2057 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
2058 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
2060 CRM_Core_DAO
::executeQuery($sql);
2063 $del->custom_group_id
= $oldGroup->id
;
2064 self
::createField($del, 'delete');
2068 CRM_Utils_System
::flushCache();
2072 * Get the database table name and column name for a custom field
2074 * @param int $fieldID - the fieldID of the custom field
2075 * @param boolean $force - force the sql to be run again (primarily used for tests)
2077 * @return array - fatal is fieldID does not exists, else array of tableName, columnName
2081 static function getTableColumnGroup($fieldID, $force = FALSE) {
2082 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2083 $cache = CRM_Utils_Cache
::singleton();
2084 $fieldValues = $cache->get($cacheKey);
2085 if (empty($fieldValues) ||
$force) {
2087 SELECT cg.table_name, cf.column_name, cg.id
2088 FROM civicrm_custom_group cg,
2089 civicrm_custom_field cf
2090 WHERE cf.custom_group_id = cg.id
2092 $params = array(1 => array($fieldID, 'Integer'));
2093 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2095 if (!$dao->fetch()) {
2096 CRM_Core_Error
::fatal();
2099 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2100 $cache->set($cacheKey, $fieldValues);
2102 return $fieldValues;
2106 * Function to get custom option groups
2108 * @params array $includeFieldIds ids of custom fields for which
2109 * option groups must be included.
2111 * Currently this is required in the cases where option groups are to be included
2112 * for inactive fields : CRM-5369
2116 * @param null $includeFieldIds
2118 * @return mixed $customOptionGroup@static
2120 public static function &customOptionGroup($includeFieldIds = NULL) {
2121 static $customOptionGroup = NULL;
2123 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2124 if ($cacheKey == 'force') {
2125 $customOptionGroup[$cacheKey] = NULL;
2128 if (empty($customOptionGroup[$cacheKey])) {
2129 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2131 //support for single as well as array format.
2132 if (!empty($includeFieldIds)) {
2133 if (is_array($includeFieldIds)) {
2134 $includeFieldIds = implode(',', $includeFieldIds);
2136 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2140 SELECT g.id, g.title
2141 FROM civicrm_option_group g
2142 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2143 WHERE {$whereClause}";
2145 $dao = CRM_Core_DAO
::executeQuery($query);
2146 while ($dao->fetch()) {
2147 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2151 return $customOptionGroup[$cacheKey];
2155 * Function to fix orphan groups
2157 * @params int $customFieldId custom field id
2158 * @params int $optionGroupId option group id
2162 * @param $customFieldId
2163 * @param $optionGroupId
2168 static function fixOptionGroups($customFieldId, $optionGroupId) {
2169 // check if option group belongs to any custom Field else delete
2170 // get the current option group
2171 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2175 // get the updated option group
2176 // if both are same return
2177 if ($currentOptionGroupId == $optionGroupId) {
2181 // check if option group is related to any other field
2182 self
::checkOptionGroup($currentOptionGroupId);
2186 * Function to check if option group is related to more than one
2189 * @params int $optionGroupId option group id
2191 * @param $optionGroupId
2196 static function checkOptionGroup($optionGroupId) {
2199 FROM civicrm_custom_field
2200 WHERE option_group_id = {$optionGroupId}";
2202 $count = CRM_Core_DAO
::singleValueQuery($query);
2205 //delete the option group
2206 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2211 * @param $optionGroupId
2214 * @return null|string
2216 static function getOptionGroupDefault($optionGroupId, $htmlType) {
2218 SELECT default_value, html_type
2219 FROM civicrm_custom_field
2220 WHERE option_group_id = {$optionGroupId}
2221 AND default_value IS NOT NULL
2222 ORDER BY html_type";
2224 $dao = CRM_Core_DAO
::executeQuery($query);
2225 $defaultValue = NULL;
2226 $defaultHTMLType = NULL;
2227 while ($dao->fetch()) {
2228 if ($dao->html_type
== $htmlType) {
2229 return $dao->default_value
;
2231 if ($defaultValue == NULL) {
2232 $defaultValue = $dao->default_value
;
2233 $defaultHTMLType = $dao->html_type
;
2237 // some conversions are needed if either the old or new has a html type which has potential
2238 // multiple default values.
2239 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2240 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2242 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2244 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2245 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2247 $defaultValue = substr($defaultValue, 1, -1);
2248 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2249 substr($defaultValue, 1, -1)
2251 $defaultValue = $values[0];
2254 return $defaultValue;
2259 * @param $customFields
2261 * @param $customFieldExtends
2262 * @param bool $inline
2266 static function postProcess(&$params,
2269 $customFieldExtends,
2272 $customData = array();
2274 foreach ($params as $key => $value) {
2275 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2277 // for autocomplete transfer hidden value instead of label
2278 if ($params[$key] && isset($params[$key . '_id'])) {
2279 $value = $params[$key . '_id'];
2282 // we need to append time with date
2283 if ($params[$key] && isset($params[$key . '_time'])) {
2284 $value .= ' ' . $params[$key . '_time'];
2287 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2290 $customFieldExtends,
2291 $customFieldInfo[1],
2306 static function buildOption($field, &$options) {
2307 // Fixme - adding anything but options to the $options array is a bad idea
2308 // What if an option had the key 'attributes'?
2309 $options['attributes'] = array(
2310 'label' => $field['label'],
2311 'data_type' => $field['data_type'],
2312 'html_type' => $field['html_type'],
2315 $optionGroupID = NULL;
2316 if (($field['html_type'] == 'CheckBox' ||
2317 $field['html_type'] == 'Radio' ||
2318 $field['html_type'] == 'Select' ||
2319 $field['html_type'] == 'AdvMulti-Select' ||
2320 $field['html_type'] == 'Multi-Select' ||
2321 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2323 if ($field['option_group_id']) {
2324 $optionGroupID = $field['option_group_id'];
2326 elseif ($field['data_type'] != 'Boolean') {
2327 CRM_Core_Error
::fatal();
2331 // build the cache for custom values with options (label => value)
2332 if ($optionGroupID != NULL) {
2335 FROM civicrm_option_value
2336 WHERE option_group_id = $optionGroupID
2339 $dao = CRM_Core_DAO
::executeQuery($query);
2340 while ($dao->fetch()) {
2341 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2342 $num = round($dao->value
, 2);
2343 $options["$num"] = $dao->label
;
2346 $options[$dao->value
] = $dao->label
;
2350 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2355 * @param $fieldLabel
2356 * @param null $groupTitle
2360 static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2361 $params = array(1 => array($fieldLabel, 'String'));
2363 $params[2] = array($groupTitle, 'String');
2366 FROM civicrm_custom_field f
2367 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2368 WHERE ( f.label = %1 OR f.name = %1 )
2369 AND ( g.title = %2 OR g.name = %2 )
2375 FROM civicrm_custom_field f
2376 WHERE ( f.label = %1 OR f.name = %1 )
2380 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2381 if ($dao->fetch() &&
2392 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2395 static function getNameFromID($ids) {
2396 if (is_array($ids)) {
2397 $ids = implode(',', $ids);
2400 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2401 FROM civicrm_custom_field f
2402 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2403 WHERE f.id IN ($ids)";
2406 $dao = CRM_Core_DAO
::executeQuery($sql);
2408 while ($dao->fetch()) {
2409 $result[$dao->id
] = array(
2410 'field_name' => $dao->field_name
,
2411 'field_label' => $dao->field_label
,
2412 'group_name' => $dao->group_name
,
2413 'group_title' => $dao->group_title
,
2420 * Validate custom data.
2422 * @param array $params custom data submitted.
2423 * ie array( 'custom_1' => 'validate me' );
2425 * @return array $errors validation errors.
2428 static function validateCustomData($params) {
2430 if (!is_array($params) ||
empty($params)) {
2435 //pick up profile fields.
2436 $profileFields = array();
2437 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2439 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2441 CRM_Core_Action
::VIEW
2445 //lets start w/ params.
2446 foreach ($params as $key => $value) {
2447 $customFieldID = self
::getKeyID($key);
2448 if (!$customFieldID) {
2452 //load the structural info for given field.
2453 $field = new CRM_Core_DAO_CustomField();
2454 $field->id
= $customFieldID;
2455 if (!$field->find(TRUE)) {
2458 $dataType = $field->data_type
;
2460 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2461 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2462 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2464 $fieldTitle = $field->label
;
2467 //no need to validate.
2468 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2472 //lets validate first for required field.
2473 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2474 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2478 //now time to take care of custom field form rules.
2479 $ruleName = $errorMsg = NULL;
2480 switch ($dataType) {
2482 $ruleName = 'integer';
2483 $errorMsg = ts('%1 must be an integer (whole number).',
2484 array(1 => $fieldTitle)
2489 $ruleName = 'money';
2490 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2491 array(1 => $fieldTitle)
2496 $ruleName = 'numeric';
2497 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2498 array(1 => $fieldTitle)
2503 $ruleName = 'wikiURL';
2504 $errorMsg = ts('%1 must be valid Website.',
2505 array(1 => $fieldTitle)
2510 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2512 $funName = "CRM_Utils_Rule::{$ruleName}";
2513 if (is_callable($funName)) {
2514 $valid = call_user_func($funName, $value);
2517 $errors[$key] = $errorMsg;
2530 static function isMultiRecordField($customId) {
2531 $isMultipleWithGid = FALSE;
2532 if (!is_numeric($customId)) {
2533 $customId = self
::getKeyID($customId);
2535 if (is_numeric($customId)) {
2536 $sql = "SELECT cg.id cgId
2537 FROM civicrm_custom_group cg
2538 INNER JOIN civicrm_custom_field cf
2539 ON cg.id = cf.custom_group_id
2540 WHERE cf.id = %1 AND cg.is_multiple = 1";
2541 $params[1] = array($customId, 'Integer');
2542 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2543 if ($dao->fetch()) {
2545 $isMultipleWithGid = $dao->cgId
;
2550 return $isMultipleWithGid;