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;
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 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 (!empty($params['id'])) {
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 (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
185 $params['default_value'] = $params['option_value'][$params['default_option']];
191 $transaction = new CRM_Core_Transaction();
192 // create any option group & values if required
193 if ($params['html_type'] != 'Text' &&
194 in_array($params['data_type'], array(
195 'String', 'Int', 'Float', 'Money'))
198 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
199 $params['custom_group_id'],
204 if ($params['option_type'] == 1) {
205 // first create an option group for this custom group
206 $optionGroup = new CRM_Core_DAO_OptionGroup();
207 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
208 $optionGroup->title
= $params['label'];
209 $optionGroup->is_active
= 1;
210 $optionGroup->save();
211 $params['option_group_id'] = $optionGroup->id
;
212 if(!empty($params['option_value']) && is_array($params['option_value'])){
213 foreach ($params['option_value'] as $k => $v) {
214 if (strlen(trim($v))) {
215 $optionValue = new CRM_Core_DAO_OptionValue();
216 $optionValue->option_group_id
= $optionGroup->id
;
217 $optionValue->label
= $params['option_label'][$k];
218 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$k]);
219 switch ($params['data_type']) {
221 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($v);
225 $optionValue->value
= intval($v);
229 $optionValue->value
= floatval($v);
233 $optionValue->value
= trim($v);
236 $optionValue->weight
= $params['option_weight'][$k];
237 $optionValue->is_active
= CRM_Utils_Array
::value($k, $params['option_status'], FALSE);
238 $optionValue->save();
245 // check for orphan option groups
246 if (!empty($params['option_group_id'])) {
247 if (!empty($params['id'])) {
248 self
::fixOptionGroups($params['id'], $params['option_group_id']);
251 // if we dont have a default value
252 // retrive it from one of the other custom fields which use this option group
253 if (empty($params['default_value'])) {
254 //don't insert only value separator as default value, CRM-4579
255 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
259 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
262 $params['default_value'] = $defaultValue;
267 // since we need to save option group id :)
268 if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
269 $params['attributes'] = 'rows=4, cols=60';
272 $customField = new CRM_Core_DAO_CustomField();
273 $customField->copyValues($params);
274 $customField->is_required
= CRM_Utils_Array
::value('is_required', $params, FALSE);
275 $customField->is_searchable
= CRM_Utils_Array
::value('is_searchable', $params, FALSE);
276 $customField->in_selector
= CRM_Utils_Array
::value('in_selector', $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 (!empty($params['id'])) {
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; empty is a synonym for "all contact data types"
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 (empty($customDataType)) {
390 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
392 if ($customDataType && !is_array($customDataType)) {
394 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
395 // This is the case when getFieldsForImport() requires fields
396 // limited strictly to a subtype.
397 $customDataSubType = $customDataType;
398 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
402 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
403 // this makes the method flexible to support retrieving fields
404 // for multiple extends value.
405 $customDataType = array($customDataType);
409 if ($customDataSubType && !is_array($customDataSubType)) {
410 $customDataSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
411 trim($customDataSubType, CRM_Core_DAO
::VALUE_SEPARATOR
)
415 if (is_array($customDataType)) {
416 $cacheKey = implode('_', $customDataType);
419 $cacheKey = $customDataType;
422 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
423 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
424 $cacheKey .= $showAll ?
'_1' : '_0';
425 $cacheKey .= $inline ?
'_1_' : '_0_';
426 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
427 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
428 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
430 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
432 // also get the permission stuff here
433 if ($checkPermission) {
434 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
439 $permissionClause = '(1)';
442 // lets md5 permission clause and take first 8 characters
443 $cacheKey .= substr(md5($permissionClause), 0, 8);
445 if (strlen($cacheKey) > 40) {
446 $cacheKey = md5($cacheKey);
449 if (!self
::$_importFields ||
450 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
452 if (!self
::$_importFields) {
453 self
::$_importFields = array();
456 // check if we can retrieve from database cache
457 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
459 if ($fields === NULL) {
460 $cfTable = self
::getTableName();
463 if (is_array($customDataType)) {
465 foreach ($customDataType as $dataType) {
466 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
467 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
468 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
471 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
473 $value = $value ?
$value . ", {$val}" : $val;
477 $extends = "AND $cgTable.extends IN ( $value ) ";
481 if (!empty($customDataType) && empty($extends)) {
482 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
483 self
::$_importFields[$cacheKey] = array();
484 return self
::$_importFields[$cacheKey];
488 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
491 $query = "SELECT $cfTable.id, $cfTable.label,
495 $cfTable.default_value,
496 $cfTable.options_per_line, $cfTable.text_length,
497 $cfTable.custom_group_id,
498 $cgTable.extends, $cfTable.is_search_range,
499 $cgTable.extends_entity_column_value,
500 $cgTable.extends_entity_column_id,
502 $cfTable.option_group_id,
503 $cfTable.date_format,
504 $cfTable.time_format,
508 ON $cfTable.custom_group_id = $cgTable.id
512 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
516 $query .= " AND $cgTable.style = 'Inline' ";
519 //get the custom fields for specific type in
520 //combination with fields those support any type.
521 if (!empty($customDataSubType)) {
522 $subtypeClause = array();
523 foreach ($customDataSubType as $subtype) {
524 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
525 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
528 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
530 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
533 if ($customDataSubName) {
534 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
537 // also get the permission stuff here
538 if ($checkPermission) {
539 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
544 $permissionClause = '(1)';
547 $query .= " $extends AND $permissionClause
548 ORDER BY $cgTable.weight, $cgTable.title,
549 $cfTable.weight, $cfTable.label";
551 $dao = CRM_Core_DAO
::executeQuery($query);
554 while (($dao->fetch()) != NULL) {
555 $fields[$dao->id
]['label'] = $dao->label
;
556 $fields[$dao->id
]['groupTitle'] = $dao->title
;
557 $fields[$dao->id
]['data_type'] = $dao->data_type
;
558 $fields[$dao->id
]['html_type'] = $dao->html_type
;
559 $fields[$dao->id
]['default_value'] = $dao->default_value
;
560 $fields[$dao->id
]['text_length'] = $dao->text_length
;
561 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
562 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
563 $fields[$dao->id
]['extends'] = $dao->extends;
564 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
565 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
566 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
567 $fields[$dao->id
]['is_view'] = $dao->is_view
;
568 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
569 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
570 $fields[$dao->id
]['date_format'] = $dao->date_format
;
571 $fields[$dao->id
]['time_format'] = $dao->time_format
;
574 CRM_Core_BAO_Cache
::setItem($fields,
576 "custom importableFields $cacheKey"
579 self
::$_importFields[$cacheKey] = $fields;
582 return self
::$_importFields[$cacheKey];
586 * Return the field ids and names (with groups) for import purpose.
588 * @param int|string $contactType Contact type
589 * @param boolean $showAll If true returns all fields (includes disabled fields)
590 * @param boolean $onlyParent return fields ONLY related to basic types
591 * @param boolean $search when called from search and multiple records need to be returned
592 * @param boolean $checkPermission if false, do not include permissioning clause
594 * @param bool $withMultiple
596 * @return array $fields -
601 public static function &getFieldsForImport($contactType = 'Individual',
605 $checkPermission = TRUE,
606 $withMultiple = FALSE
608 // Note: there are situations when we want getFieldsForImport() return fields related
609 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
610 $fields = &self
::getFields($contactType,
620 $importableFields = array();
621 foreach ($fields as $id => $values) {
622 // for now we should not allow multiple fields in profile / export etc, hence unsetting
624 (!empty($values['is_multiple']) && !$withMultiple)
629 /* generate the key for the fields array */
633 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
634 $importableFields[$key] = array(
636 'title' => CRM_Utils_Array
::value('label', $values),
637 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
639 'custom_field_id' => $id,
640 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
641 'data_type' => CRM_Utils_Array
::value('data_type', $values),
642 'html_type' => CRM_Utils_Array
::value('html_type', $values),
643 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
646 // CRM-6681, pass date and time format when html_type = Select Date
647 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
648 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
649 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
653 return $importableFields;
657 * Get the field id from an import key
659 * @param string $key The key to parse
662 * @return int|null The id (if exists)
666 public static function getKeyID($key, $all = FALSE) {
668 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
675 CRM_Utils_Array
::value(2, $match),
684 * Use the cache to get all values of a specific custom field
686 * @param int $fieldID the custom field ID
688 * @return CRM_Core_DAO_CustomField $field the field object
692 static function getFieldObject($fieldID) {
693 $field = new CRM_Core_DAO_CustomField();
695 // check if we can get the field values from the system cache
696 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
697 $cache = CRM_Utils_Cache
::singleton();
698 $fieldValues = $cache->get($cacheKey);
699 if (empty($fieldValues)) {
700 $field->id
= $fieldID;
701 if (!$field->find(TRUE)) {
702 CRM_Core_Error
::fatal();
705 $fieldValues = array();
706 CRM_Core_DAO
::storeValues($field, $fieldValues);
708 $cache->set($cacheKey, $fieldValues);
711 $field->copyValues($fieldValues);
718 * This function for building custom fields
720 * @param CRM_Core_Form $qf form object (reference)
721 * @param string $elementName name of the custom field
723 * @param boolean $inactiveNeeded
724 * @param bool $useRequired
725 * @param boolean $search true if used for search else false
726 * @param string $label label for custom field
728 * @internal param bool $userRequired true if required else false
732 public static function addQuickFormElement(&$qf,
735 $inactiveNeeded = FALSE,
740 $field = self
::getFieldObject($fieldId);
742 // Custom field HTML should indicate group+field name
743 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
744 $dataCrmCustomVal = $groupName.':'.$field->name
;
745 $dataCrmCustomAttr = 'data-crm-custom="'.$dataCrmCustomVal.'"';
746 $field->attributes
.= $dataCrmCustomAttr;
748 // Fixed for Issue CRM-2183
749 if ($field->html_type
== 'TextArea' && $search) {
750 $field->html_type
= 'Text';
753 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
755 // FIXME: Why are select state/country separate widget types?
756 if (in_array($field->html_type
, array('Select', 'Multi-Select', 'Select State/Province', 'Multi-Select State/Province', 'Select Country', 'Multi-Select Country'))) {
757 $selectAttributes = array(
758 'data-crm-custom' => $dataCrmCustomVal,
759 'class' => 'crm-select2',
761 if (strpos($field->html_type
, 'Multi') === 0) {
762 $selectAttributes['multiple'] = 'multiple';
765 // Add data so popup link. Normally this is handled by CRM_Core_Form->addSelect
766 if ($field->option_group_id
&& !$search && in_array($field->html_type
, array('Select', 'Multi-Select')) && CRM_Core_Permission
::check('administer CiviCRM')) {
767 $selectAttributes +
= array(
768 'data-api-entity' => 'contact', // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
769 'data-api-field' => 'custom_' . $field->id
,
770 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
774 if (!isset($label)) {
775 $label = $field->label
;
779 * at some point in time we might want to split the below into small functions
782 switch ($field->html_type
) {
784 if ($field->is_search_range
&& $search) {
785 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
786 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
789 $element = &$qf->add(strtolower($field->html_type
), $elementName, $label,
791 $useRequired && !$search
797 $attributes = $dataCrmCustomAttr;
798 if ($field->note_rows
) {
799 $attributes .= 'rows=' . $field->note_rows
;
802 $attributes .= 'rows=4';
804 if ($field->note_columns
) {
805 $attributes .= ' cols=' . $field->note_columns
;
808 $attributes .= ' cols=60';
810 if ($field->text_length
) {
811 $attributes .= ' maxlength=' . $field->text_length
;
813 $element = &$qf->add(strtolower($field->html_type
),
817 $useRequired && !$search
822 if ($field->is_search_range
&& $search) {
823 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
825 'format' => $field->date_format
,
826 'timeFormat' => $field->time_format
,
827 'startOffset' => $field->start_date_years
,
828 'endOffset' => $field->end_date_years
,
829 'data-crm-custom' => $dataCrmCustomVal,
833 $qf->addDate($elementName . '_to', ts('To'), FALSE,
835 'format' => $field->date_format
,
836 'timeFormat' => $field->time_format
,
837 'startOffset' => $field->start_date_years
,
838 'endOffset' => $field->end_date_years
,
839 'data-crm-custom' => $dataCrmCustomVal,
844 $required = $useRequired && !$search;
846 $qf->addDate($elementName, $label, $required, array(
847 'format' => $field->date_format
,
848 'timeFormat' => $field->time_format
,
849 'startOffset' => $field->start_date_years
,
850 'endOffset' => $field->end_date_years
,
851 'data-crm-custom' => $dataCrmCustomVal,
858 if ($field->data_type
!= 'Boolean') {
859 $customOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
860 $field->option_group_id
862 foreach ($customOption as $v => $l) {
863 $choice[] = $qf->createElement('radio', NULL, '', $l, (string)$v, $field->attributes
);
865 $group = $qf->addGroup($choice, $elementName, $label);
868 $choice[] = $qf->createElement('radio', NULL, '', ts('Yes'), '1', $field->attributes
);
869 $choice[] = $qf->createElement('radio', NULL, '', ts('No'), '0', $field->attributes
);
870 $group = $qf->addGroup($choice, $elementName, $label);
872 if ($useRequired && !$search) {
873 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
876 $group->setAttribute('allowClear', TRUE);
881 $selectOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
882 $field->option_group_id
885 $qf->add('select', $elementName, $label,
886 array('' => $placeholder) +
$selectOption,
887 $useRequired && !$search,
892 //added for select multiple
894 case 'AdvMulti-Select':
895 $selectOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
896 $field->option_group_id
899 count($selectOption) > 1
901 $selectOption['CiviCRM_OP_OR'] = ts('Select to match ANY; unselect to match ALL');
904 $include =& $qf->addElement(
907 $label, $selectOption,
911 'class' => 'advmultiselect',
912 'data-crm-custom' => $dataCrmCustomVal,
916 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
917 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
919 if ($useRequired && !$search) {
920 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
925 $selectOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
926 $field->option_group_id
929 count($selectOption) > 1
931 $selectOption['CiviCRM_OP_OR'] = ts('Select to match ANY; unselect to match ALL');
933 $qf->addElement('select', $elementName, $label, $selectOption, $selectAttributes);
935 if ($useRequired && !$search) {
936 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
941 $customOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
942 $field->option_group_id
945 foreach ($customOption as $v => $l) {
946 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
951 $check[] = &$qf->addElement('advcheckbox', 'CiviCRM_OP_OR', NULL, ts('Check to match ANY; uncheck to match ALL'), array('data-crm-custom' => $dataCrmCustomVal));
953 $qf->addGroup($check, $elementName, $label);
954 if ($useRequired && !$search) {
955 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
960 // we should not build upload file in search mode
965 strtolower($field->html_type
),
969 $useRequired && !$search
971 $qf->addUploadElement($elementName);
974 case 'Select State/Province':
976 $stateOption = array('' => $placeholder) + CRM_Core_PseudoConstant
::stateProvince();
977 $qf->add('select', $elementName, $label, $stateOption,
978 $useRequired && !$search,
981 $qf->_stateCountryMap
['state_province'][] = $elementName;
984 case 'Multi-Select State/Province':
985 //Add Multi-select State/Province
986 $stateOption = CRM_Core_PseudoConstant
::stateProvince();
988 $qf->addElement('select', $elementName, $label, $stateOption, $selectAttributes);
989 if ($useRequired && !$search) {
990 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
994 case 'Select Country':
996 $countryOption = array('' => $placeholder) + CRM_Core_PseudoConstant
::country();
997 $qf->add('select', $elementName, $label, $countryOption,
998 $useRequired && !$search,
1001 $qf->_stateCountryMap
['country'][] = $elementName;
1004 case 'Multi-Select Country':
1006 $countryOption = CRM_Core_PseudoConstant
::country();
1007 $qf->addElement('select', $elementName, $label, $countryOption, $selectAttributes);
1008 if ($useRequired && !$search) {
1009 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
1013 case 'RichTextEditor':
1014 $attributes = array('rows' => $field->note_rows
, 'cols' => $field->note_columns
, 'data-crm-custom' => $dataCrmCustomVal);
1015 if ($field->text_length
) {
1016 $attributes['maxlength'] = $field->text_length
;
1018 $qf->addWysiwyg($elementName, $label, $attributes, $search);
1021 case 'Autocomplete-Select':
1022 static $customUrls = array();
1023 // Fixme: why is this a string in the first place??
1024 $attributes = array();
1025 if ($field->attributes
) {
1026 foreach(explode(' ', $field->attributes
) as $at) {
1027 if (strpos($at, '=')) {
1028 list($k, $v) = explode('=', $at);
1029 $attributes[$k] = trim($v, ' "');
1033 if ($field->data_type
== 'ContactReference') {
1034 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1035 $attributes['data-api-entity'] = 'contact';
1036 $qf->add('text', $elementName, $label, $attributes,
1037 $useRequired && !$search
1040 $urlParams = "context=customfield&id={$field->id}";
1042 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1049 // FIXME: This won't work with customFieldOptions hook
1050 $attributes +
= array(
1051 'entity' => 'option_value',
1052 'placeholder' => $placeholder,
1054 'params' => array('option_group_id' => $field->option_group_id
),
1057 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1060 $qf->assign('customUrls', $customUrls);
1064 switch ($field->data_type
) {
1066 // integers will have numeric rule applied to them.
1067 if ($field->is_search_range
&& $search) {
1068 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1069 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1072 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1077 if ($field->is_search_range
&& $search) {
1078 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1079 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1082 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1087 if ($field->is_search_range
&& $search) {
1088 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1089 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1092 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1102 'onfocus' => "if (!this.value) { this.value='http://';} else return false",
1103 'onblur' => "if ( this.value == 'http://') { this.value='';} else return false",
1104 'data-crm-custom' => $dataCrmCustomVal,
1106 $useRequired && !$search
1108 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1111 if ($field->is_view
&& !$search) {
1112 $qf->freeze($elementName);
1117 * Delete the Custom Field.
1119 * @param object $field - the field object
1127 public static function deleteField($field) {
1128 CRM_Utils_System
::flushCache();
1130 // first delete the custom option group and values associated with this field
1131 if ($field->option_group_id
) {
1132 //check if option group is related to any other field, if
1133 //not delete the option group and related option values
1134 self
::checkOptionGroup($field->option_group_id
);
1137 // next drop the column from the custom value table
1138 self
::createField($field, 'delete');
1141 CRM_Core_BAO_UFField
::delUFField($field->id
);
1142 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1148 * Given a custom field value, its id and the set of options
1149 * find the display value for this field
1151 * @param mixed $value the custom field value
1152 * @param int $id the custom field id
1153 * @param int $options the assoc array of option name/value pairs
1155 * @param null $contactID
1156 * @param null $fieldID
1158 * @return string the display value
1163 static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1164 $option = &$options[$id];
1165 $attributes = &$option['attributes'];
1166 $html_type = $attributes['html_type'];
1167 $data_type = $attributes['data_type'];
1168 $format = CRM_Utils_Array
::value('format', $attributes);
1170 return self
::getDisplayValueCommon($value,
1180 static function getDisplayValueCommon($value,
1191 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1192 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1193 $html_type == 'Select' ||
1194 $html_type == 'CheckBox' ||
1195 $html_type == 'AdvMulti-Select' ||
1196 $html_type == 'Multi-Select'
1199 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1202 switch ($html_type) {
1204 if ($data_type == 'Boolean') {
1205 // Do not assume that if not yes means no.
1208 $display = ts('Yes');
1210 elseif ((string)$value === '0') {
1211 $display = ts('No');
1215 $display = CRM_Utils_Array
::value($value, $option);
1219 case 'Autocomplete-Select':
1220 if ($data_type == 'ContactReference' &&
1223 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1226 $display = CRM_Utils_Array
::value($value, $option);
1231 $display = CRM_Utils_Array
::value($value, $option);
1235 case 'AdvMulti-Select':
1236 case 'Multi-Select':
1237 if (is_array($value)) {
1238 $checkedData = $value;
1241 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1242 substr($value, 1, -1)
1244 if ($html_type == 'CheckBox') {
1246 foreach ($checkedData as $v) {
1249 $checkedData = $newData;
1255 foreach ($checkedData as $key => $val) {
1256 if ($key === 'CiviCRM_OP_OR') {
1260 if ($html_type == 'CheckBox') {
1263 $v[] = CRM_Utils_Array
::value($key, $option);
1268 $v[] = CRM_Utils_Array
::value($val, $option);
1272 $display = implode(', ', $v);
1277 if (is_array($value)) {
1278 foreach ($value as $key => $val) {
1279 $display[$key] = CRM_Utils_Date
::customFormat($val);
1283 // remove time element display if time is not set
1284 if (empty($option['attributes']['time_format'])) {
1285 $value = substr($value, 0, 10);
1287 $display = CRM_Utils_Date
::customFormat($value);
1291 case 'Select State/Province':
1292 if (empty($value)) {
1296 $display = CRM_Core_PseudoConstant
::stateProvince($value);
1300 case 'Multi-Select State/Province':
1301 if (is_array($value)) {
1302 $checkedData = $value;
1305 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1306 substr($value, 1, -1)
1310 $states = CRM_Core_PseudoConstant
::stateProvince();
1312 foreach ($checkedData as $stateID) {
1316 $display .= $states[$stateID];
1320 case 'Select Country':
1321 if (empty($value)) {
1325 $display = CRM_Core_PseudoConstant
::country($value);
1329 case 'Multi-Select Country':
1330 if (is_array($value)) {
1331 $checkedData = $value;
1334 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1335 substr($value, 1, -1)
1339 $countries = CRM_Core_PseudoConstant
::country();
1341 foreach ($checkedData as $countryID) {
1345 $display .= $countries[$countryID];
1351 $url = self
::getFileURL($contactID, $fieldID, $value);
1353 $display = $url['file_url'];
1359 if (empty($value)) {
1363 $display = nl2br($value);
1368 if (empty($value)) {
1375 return $display ?
$display : $value;
1379 * Function to set default values for custom data used in profile
1381 * @params int $customFieldId custom field id
1382 * @params string $elementName custom field name
1383 * @params array $defaults associated array of fields
1384 * @params int $contactId contact id
1385 * @param $customFieldId
1386 * @param $elementName
1388 * @param null $contactId
1389 * @param int $mode profile mode
1390 * @param mixed $value if passed - dont fetch value from db,
1391 * just format the given value
1396 static function setProfileDefaults($customFieldId,
1403 //get the type of custom field
1404 $customField = new CRM_Core_BAO_CustomField();
1405 $customField->id
= $customFieldId;
1406 $customField->find(TRUE);
1409 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1410 $value = $customField->default_value
;
1414 if (!isset($value)) {
1415 $info = self
::getTableColumnGroup($customFieldId);
1416 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1417 $result = CRM_Core_DAO
::executeQuery($query);
1418 if ($result->fetch()) {
1419 $value = $result->value
;
1423 if ($customField->data_type
== 'Country') {
1425 $config = CRM_Core_Config
::singleton();
1426 if ($config->defaultContactCountry
) {
1427 $value = $config->defaultContactCountry();
1433 //set defaults if mode is registration
1434 if (!trim($value) &&
1436 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1438 $value = $customField->default_value
;
1441 if ($customField->data_type
== 'Money' && isset($value)) {
1442 $value = number_format($value, 2);
1444 switch ($customField->html_type
) {
1446 case 'AdvMulti-Select':
1447 case 'Multi-Select':
1448 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1449 $defaults[$elementName] = array();
1450 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1451 substr($value, 1, -1)
1453 foreach ($customOption as $val) {
1454 if (in_array($val['value'], $checkedValue)) {
1455 if ($customField->html_type
== 'CheckBox') {
1456 $defaults[$elementName][$val['value']] = 1;
1458 elseif ($customField->html_type
== 'Multi-Select' ||
1459 $customField->html_type
== 'AdvMulti-Select'
1461 $defaults[$elementName][$val['value']] = $val['value'];
1469 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1472 $customField->date_format
,
1473 $customField->time_format
1478 case 'Autocomplete-Select':
1479 if ($customField->data_type
== 'ContactReference') {
1480 if (is_numeric($value)) {
1481 $defaults[$elementName . '_id'] = $value;
1482 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1486 $defaults[$elementName] = $value;
1491 $defaults[$elementName] = $value;
1495 static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE) {
1498 $params = array('id' => $cfID);
1499 $defaults = array();
1500 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1501 $columnName = $defaults['column_name'];
1503 //table name of custom data
1504 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1505 $defaults['custom_group_id'],
1509 //query to fetch id from civicrm_file
1510 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1511 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1516 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1521 $result['file_id'] = $fileID;
1523 if ($fileType == 'image/jpeg' ||
1524 $fileType == 'image/pjpeg' ||
1525 $fileType == 'image/gif' ||
1526 $fileType == 'image/x-png' ||
1527 $fileType == 'image/png'
1529 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1534 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1535 list($imageWidth, $imageHeight) = getimagesize($path);
1536 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1537 $url = CRM_Utils_System
::url('civicrm/file',
1538 "reset=1&id=$fileID&eid=$contactID",
1539 $absolute, NULL, TRUE, TRUE
1541 $result['file_url'] = "
1542 <a href=\"$url\" class='crm-image-popup'>
1543 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1545 // for non image files
1548 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1552 $url = CRM_Utils_System
::url('civicrm/file',
1553 "reset=1&id=$fileID&eid=$contactID",
1554 $absolute, NULL, TRUE, TRUE
1556 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1564 * Format custom fields before inserting
1566 * @param int $customFieldId custom field id
1567 * @param array $customFormatted formatted array
1568 * @param mix $value value of custom field
1569 * @param string $customFieldExtend custom field extends
1570 * @param int $customValueId custom option value id
1571 * @param int $entityId entity id (contribution, membership...)
1572 * @param boolean $inline consider inline custom groups only
1573 * @param boolean $checkPermission if false, do not include permissioning clause
1575 * @return array $customFormatted formatted custom field array
1578 static function formatCustomField($customFieldId, &$customFormatted, $value,
1579 $customFieldExtend, $customValueId = NULL,
1582 $checkPermission = TRUE
1584 //get the custom fields for the entity
1585 //subtype and basic type
1586 $customDataSubType = NULL;
1587 if (is_array($customFieldExtend)) {
1588 $customFieldExtend = $customFieldExtend[0];
1591 if (in_array($customFieldExtend,
1592 CRM_Contact_BAO_ContactType
::subTypes()
1594 // This is the case when getFieldsForImport() requires fields
1595 // of subtype and its parent.CRM-5143
1596 $customDataSubType = $customFieldExtend;
1597 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1600 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1610 if (!array_key_exists($customFieldId, $customFields)) {
1614 // return if field is a 'code' field
1615 if (!empty($customFields[$customFieldId]['is_view'])) {
1619 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1621 if (!$customValueId &&
1622 // we always create new entites for is_multiple unless specified
1623 !$customFields[$customFieldId]['is_multiple'] &&
1629 WHERE entity_id={$entityId}";
1631 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1634 //fix checkbox, now check box always submits values
1635 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1637 // Note that only during merge this is not an array, and you can directly use value
1638 if (is_array($value)) {
1639 $selectedValues = array();
1640 foreach ($value as $selId => $val) {
1642 $selectedValues[] = $selId;
1645 if (!empty($selectedValues)) {
1646 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1648 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1657 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1658 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1661 // Note that only during merge this is not an array,
1662 // and you can directly use value, CRM-4385
1663 if (is_array($value)) {
1664 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1665 array_values($value)
1666 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1674 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1675 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1676 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1678 $customFields[$customFieldId]['data_type'] == 'String' &&
1679 !empty($customFields[$customFieldId]['text_length']) &&
1682 // lets make sure that value is less than the length, else we'll
1683 // be losing some data, CRM-7481
1684 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1685 // need to do a few things here
1687 // 1. lets find a new length
1688 $newLength = $customFields[$customFieldId]['text_length'];
1689 $minLength = strlen($value);
1690 while ($newLength < $minLength) {
1691 $newLength = $newLength * 2;
1694 // set the custom field meta data to have a length larger than value
1695 // alter the custom value table column to match this length
1696 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1701 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1702 if (!CRM_Utils_System
::isNull($value)) {
1703 $format = $customFields[$customFieldId]['date_format'];
1704 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1709 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1710 $customFields[$customFieldId]['data_type'] == 'Money'
1716 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1717 $value = CRM_Utils_Rule
::cleanMoney($value);
1721 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1722 $customFields[$customFieldId]['data_type'] == 'Country'
1732 if ($customFields[$customFieldId]['data_type'] == 'File') {
1733 if (empty($value)) {
1737 $config = CRM_Core_Config
::singleton();
1739 $fName = $value['name'];
1740 $mimeType = $value['type'];
1742 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1744 // rename this file to go into the secure directory
1745 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1746 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1749 if ($customValueId) {
1754 $params = array(1 => array($customValueId, 'Integer'));
1755 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1758 $fileDAO = new CRM_Core_DAO_File();
1761 $fileDAO->id
= $fileId;
1764 $fileDAO->uri
= $filename;
1765 $fileDAO->mime_type
= $mimeType;
1766 $fileDAO->upload_date
= date('Ymdhis');
1768 $fileId = $fileDAO->id
;
1772 if (!is_array($customFormatted)) {
1773 $customFormatted = array();
1776 if (!array_key_exists($customFieldId, $customFormatted)) {
1777 $customFormatted[$customFieldId] = array();
1781 if ($customValueId) {
1782 $index = $customValueId;
1785 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1786 $customFormatted[$customFieldId][$index] = array();
1788 $customFormatted[$customFieldId][$index] = array(
1789 'id' => $customValueId > 0 ?
$customValueId : NULL,
1791 'type' => $customFields[$customFieldId]['data_type'],
1792 'custom_field_id' => $customFieldId,
1793 'custom_group_id' => $groupID,
1794 'table_name' => $tableName,
1795 'column_name' => $columnName,
1796 'file_id' => $fileId,
1797 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1800 //we need to sort so that custom fields are created in the order of entry
1801 krsort($customFormatted[$customFieldId]);
1802 return $customFormatted;
1805 static function &defaultCustomTableSchema(&$params) {
1806 // add the id and extends_id
1808 'name' => $params['name'],
1809 'is_multiple' => $params['is_multiple'],
1810 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1814 'type' => 'int unsigned',
1817 'attributes' => 'AUTO_INCREMENT',
1818 'comment' => 'Default MySQL primary key',
1821 'name' => 'entity_id',
1822 'type' => 'int unsigned',
1824 'comment' => 'Table that this extends',
1825 'fk_table_name' => $params['extends_name'],
1826 'fk_field_name' => 'id',
1827 'fk_attributes' => 'ON DELETE CASCADE',
1832 if (!$params['is_multiple']) {
1833 $table['indexes'] = array(
1836 'field_name_1' => 'entity_id',
1843 static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1844 $tableName = CRM_Core_DAO
::getFieldValue(
1845 'CRM_Core_DAO_CustomGroup',
1846 $field->custom_group_id
,
1851 'table_name' => $tableName,
1852 'operation' => $operation,
1853 'name' => $field->column_name
,
1854 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1858 'required' => $field->is_required
,
1859 'searchable' => $field->is_searchable
,
1862 if ($operation == 'delete') {
1863 $fkName = "{$tableName}_{$field->column_name}";
1864 if (strlen($fkName) >= 48) {
1865 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1867 $params['fkName'] = $fkName;
1869 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1870 $params['fk_table_name'] = 'civicrm_country';
1871 $params['fk_field_name'] = 'id';
1872 $params['fk_attributes'] = 'ON DELETE SET NULL';
1874 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1875 $params['type'] = 'varchar(255)';
1877 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1878 $params['fk_table_name'] = 'civicrm_state_province';
1879 $params['fk_field_name'] = 'id';
1880 $params['fk_attributes'] = 'ON DELETE SET NULL';
1882 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1883 $params['type'] = 'varchar(255)';
1885 elseif ($field->data_type
== 'File') {
1886 $params['fk_table_name'] = 'civicrm_file';
1887 $params['fk_field_name'] = 'id';
1888 $params['fk_attributes'] = 'ON DELETE SET NULL';
1890 elseif ($field->data_type
== 'ContactReference') {
1891 $params['fk_table_name'] = 'civicrm_contact';
1892 $params['fk_field_name'] = 'id';
1893 $params['fk_attributes'] = 'ON DELETE SET NULL';
1895 if ($field->default_value
) {
1896 $params['default'] = "'{$field->default_value}'";
1899 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1903 * Determine whether it would be safe to move a field
1905 * @param int $fieldID FK to civicrm_custom_field
1906 * @param int $newGroupID FK to civicrm_custom_group
1911 static function _moveFieldValidate($fieldID, $newGroupID) {
1914 $field = new CRM_Core_DAO_CustomField();
1915 $field->id
= $fieldID;
1916 if (!$field->find(TRUE)) {
1917 $errors['fieldID'] = 'Invalid ID for custom field';
1921 $oldGroup = new CRM_Core_DAO_CustomGroup();
1922 $oldGroup->id
= $field->custom_group_id
;
1923 if (!$oldGroup->find(TRUE)) {
1924 $errors['fieldID'] = 'Invalid ID for old custom group';
1928 $newGroup = new CRM_Core_DAO_CustomGroup();
1929 $newGroup->id
= $newGroupID;
1930 if (!$newGroup->find(TRUE)) {
1931 $errors['newGroupID'] = 'Invalid ID for new custom group';
1937 FROM civicrm_custom_field a
1938 INNER JOIN civicrm_custom_field b
1940 AND a.label = b.label
1941 AND b.custom_group_id = %2
1944 1 => array($field->id
, 'Integer'),
1945 2 => array($newGroup->id
, 'Integer'),
1947 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1949 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1952 $tableName = $oldGroup->table_name
;
1953 $columnName = $field->column_name
;
1958 WHERE $columnName is not null
1960 $count = CRM_Core_DAO
::singleValueQuery($query,
1961 CRM_Core_DAO
::$_nullArray
1966 FROM civicrm_custom_group
1967 WHERE id IN ( %1, %2 )
1969 $params = array(1 => array($oldGroup->id
, 'Integer'),
1970 2 => array($newGroup->id
, 'Integer'),
1973 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1975 while ($dao->fetch()) {
1976 $extends[] = $dao->extends;
1978 if ($extends[0] != $extends[1]) {
1979 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1983 return empty($errors) ?
TRUE : $errors;
1987 * Move a custom data field from one group (table) to another
1989 * @param int $fieldID FK to civicrm_custom_field
1990 * @param int $newGroupID FK to civicrm_custom_group
1994 static function moveField($fieldID, $newGroupID) {
1995 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1996 if (TRUE !== $validation) {
1997 CRM_Core_Error
::fatal(implode(' ', $validation));
1999 $field = new CRM_Core_DAO_CustomField();
2000 $field->id
= $fieldID;
2003 $newGroup = new CRM_Core_DAO_CustomGroup();
2004 $newGroup->id
= $newGroupID;
2005 $newGroup->find(TRUE);
2007 $oldGroup = new CRM_Core_DAO_CustomGroup();
2008 $oldGroup->id
= $field->custom_group_id
;
2009 $oldGroup->find(TRUE);
2012 $add->custom_group_id
= $newGroup->id
;
2013 self
::createField($add, 'add');
2015 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
2016 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
2017 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
2019 CRM_Core_DAO
::executeQuery($sql);
2022 $del->custom_group_id
= $oldGroup->id
;
2023 self
::createField($del, 'delete');
2027 CRM_Utils_System
::flushCache();
2031 * Get the database table name and column name for a custom field
2033 * @param int $fieldID - the fieldID of the custom field
2034 * @param boolean $force - force the sql to be run again (primarily used for tests)
2036 * @return array - fatal is fieldID does not exists, else array of tableName, columnName
2040 static function getTableColumnGroup($fieldID, $force = FALSE) {
2041 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2042 $cache = CRM_Utils_Cache
::singleton();
2043 $fieldValues = $cache->get($cacheKey);
2044 if (empty($fieldValues) ||
$force) {
2046 SELECT cg.table_name, cf.column_name, cg.id
2047 FROM civicrm_custom_group cg,
2048 civicrm_custom_field cf
2049 WHERE cf.custom_group_id = cg.id
2051 $params = array(1 => array($fieldID, 'Integer'));
2052 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2054 if (!$dao->fetch()) {
2055 CRM_Core_Error
::fatal();
2058 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2059 $cache->set($cacheKey, $fieldValues);
2061 return $fieldValues;
2065 * Function to get custom option groups
2067 * @params array $includeFieldIds ids of custom fields for which
2068 * option groups must be included.
2070 * Currently this is required in the cases where option groups are to be included
2071 * for inactive fields : CRM-5369
2075 * @param null $includeFieldIds
2077 * @return mixed $customOptionGroup@static
2079 public static function &customOptionGroup($includeFieldIds = NULL) {
2080 static $customOptionGroup = NULL;
2082 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2083 if ($cacheKey == 'force') {
2084 $customOptionGroup[$cacheKey] = NULL;
2087 if (empty($customOptionGroup[$cacheKey])) {
2088 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2090 //support for single as well as array format.
2091 if (!empty($includeFieldIds)) {
2092 if (is_array($includeFieldIds)) {
2093 $includeFieldIds = implode(',', $includeFieldIds);
2095 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2099 SELECT g.id, g.title
2100 FROM civicrm_option_group g
2101 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2102 WHERE {$whereClause}";
2104 $dao = CRM_Core_DAO
::executeQuery($query);
2105 while ($dao->fetch()) {
2106 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2110 return $customOptionGroup[$cacheKey];
2114 * Function to fix orphan groups
2116 * @params int $customFieldId custom field id
2117 * @params int $optionGroupId option group id
2121 * @param $customFieldId
2122 * @param $optionGroupId
2127 static function fixOptionGroups($customFieldId, $optionGroupId) {
2128 // check if option group belongs to any custom Field else delete
2129 // get the current option group
2130 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2134 // get the updated option group
2135 // if both are same return
2136 if ($currentOptionGroupId == $optionGroupId) {
2140 // check if option group is related to any other field
2141 self
::checkOptionGroup($currentOptionGroupId);
2145 * Function to check if option group is related to more than one
2148 * @params int $optionGroupId option group id
2150 * @param $optionGroupId
2155 static function checkOptionGroup($optionGroupId) {
2158 FROM civicrm_custom_field
2159 WHERE option_group_id = {$optionGroupId}";
2161 $count = CRM_Core_DAO
::singleValueQuery($query);
2164 //delete the option group
2165 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2169 static function getOptionGroupDefault($optionGroupId, $htmlType) {
2171 SELECT default_value, html_type
2172 FROM civicrm_custom_field
2173 WHERE option_group_id = {$optionGroupId}
2174 AND default_value IS NOT NULL
2175 ORDER BY html_type";
2177 $dao = CRM_Core_DAO
::executeQuery($query);
2178 $defaultValue = NULL;
2179 $defaultHTMLType = NULL;
2180 while ($dao->fetch()) {
2181 if ($dao->html_type
== $htmlType) {
2182 return $dao->default_value
;
2184 if ($defaultValue == NULL) {
2185 $defaultValue = $dao->default_value
;
2186 $defaultHTMLType = $dao->html_type
;
2190 // some conversions are needed if either the old or new has a html type which has potential
2191 // multiple default values.
2192 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2193 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2195 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2197 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2198 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2200 $defaultValue = substr($defaultValue, 1, -1);
2201 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2202 substr($defaultValue, 1, -1)
2204 $defaultValue = $values[0];
2207 return $defaultValue;
2210 static function postProcess(&$params,
2213 $customFieldExtends,
2216 $customData = array();
2218 foreach ($params as $key => $value) {
2219 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2221 // for autocomplete transfer hidden value instead of label
2222 if ($params[$key] && isset($params[$key . '_id'])) {
2223 $value = $params[$key . '_id'];
2226 // we need to append time with date
2227 if ($params[$key] && isset($params[$key . '_time'])) {
2228 $value .= ' ' . $params[$key . '_time'];
2231 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2234 $customFieldExtends,
2235 $customFieldInfo[1],
2244 static function buildOption($field, &$options) {
2245 // Fixme - adding anything but options to the $options array is a bad idea
2246 // What if an option had the key 'attributes'?
2247 $options['attributes'] = array(
2248 'label' => $field['label'],
2249 'data_type' => $field['data_type'],
2250 'html_type' => $field['html_type'],
2253 $optionGroupID = NULL;
2254 if (($field['html_type'] == 'CheckBox' ||
2255 $field['html_type'] == 'Radio' ||
2256 $field['html_type'] == 'Select' ||
2257 $field['html_type'] == 'AdvMulti-Select' ||
2258 $field['html_type'] == 'Multi-Select' ||
2259 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2261 if ($field['option_group_id']) {
2262 $optionGroupID = $field['option_group_id'];
2264 elseif ($field['data_type'] != 'Boolean') {
2265 CRM_Core_Error
::fatal();
2269 // build the cache for custom values with options (label => value)
2270 if ($optionGroupID != NULL) {
2273 FROM civicrm_option_value
2274 WHERE option_group_id = $optionGroupID
2277 $dao = CRM_Core_DAO
::executeQuery($query);
2278 while ($dao->fetch()) {
2279 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2280 $num = round($dao->value
, 2);
2281 $options["$num"] = $dao->label
;
2284 $options[$dao->value
] = $dao->label
;
2288 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2292 static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2293 $params = array(1 => array($fieldLabel, 'String'));
2295 $params[2] = array($groupTitle, 'String');
2298 FROM civicrm_custom_field f
2299 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2300 WHERE ( f.label = %1 OR f.name = %1 )
2301 AND ( g.title = %2 OR g.name = %2 )
2307 FROM civicrm_custom_field f
2308 WHERE ( f.label = %1 OR f.name = %1 )
2312 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2313 if ($dao->fetch() &&
2324 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2327 static function getNameFromID($ids) {
2328 if (is_array($ids)) {
2329 $ids = implode(',', $ids);
2332 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2333 FROM civicrm_custom_field f
2334 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2335 WHERE f.id IN ($ids)";
2338 $dao = CRM_Core_DAO
::executeQuery($sql);
2340 while ($dao->fetch()) {
2341 $result[$dao->id
] = array(
2342 'field_name' => $dao->field_name
,
2343 'field_label' => $dao->field_label
,
2344 'group_name' => $dao->group_name
,
2345 'group_title' => $dao->group_title
,
2352 * Validate custom data.
2354 * @param array $params custom data submitted.
2355 * ie array( 'custom_1' => 'validate me' );
2357 * @return array $errors validation errors.
2360 static function validateCustomData($params) {
2362 if (!is_array($params) ||
empty($params)) {
2367 //pick up profile fields.
2368 $profileFields = array();
2369 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2371 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2373 CRM_Core_Action
::VIEW
2377 //lets start w/ params.
2378 foreach ($params as $key => $value) {
2379 $customFieldID = self
::getKeyID($key);
2380 if (!$customFieldID) {
2384 //load the structural info for given field.
2385 $field = new CRM_Core_DAO_CustomField();
2386 $field->id
= $customFieldID;
2387 if (!$field->find(TRUE)) {
2390 $dataType = $field->data_type
;
2392 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2393 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2394 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2396 $fieldTitle = $field->label
;
2399 //no need to validate.
2400 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2404 //lets validate first for required field.
2405 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2406 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2410 //now time to take care of custom field form rules.
2411 $ruleName = $errorMsg = NULL;
2412 switch ($dataType) {
2414 $ruleName = 'integer';
2415 $errorMsg = ts('%1 must be an integer (whole number).',
2416 array(1 => $fieldTitle)
2421 $ruleName = 'money';
2422 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2423 array(1 => $fieldTitle)
2428 $ruleName = 'numeric';
2429 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2430 array(1 => $fieldTitle)
2435 $ruleName = 'wikiURL';
2436 $errorMsg = ts('%1 must be valid Website.',
2437 array(1 => $fieldTitle)
2442 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2444 $funName = "CRM_Utils_Rule::{$ruleName}";
2445 if (is_callable($funName)) {
2446 $valid = call_user_func($funName, $value);
2449 $errors[$key] = $errorMsg;
2457 static function isMultiRecordField($customId) {
2458 $isMultipleWithGid = FALSE;
2459 if (!is_numeric($customId)) {
2460 $customId = self
::getKeyID($customId);
2462 if (is_numeric($customId)) {
2463 $sql = "SELECT cg.id cgId
2464 FROM civicrm_custom_group cg
2465 INNER JOIN civicrm_custom_field cf
2466 ON cg.id = cf.custom_group_id
2467 WHERE cf.id = %1 AND cg.is_multiple = 1";
2468 $params[1] = array($customId, 'Integer');
2469 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2470 if ($dao->fetch()) {
2472 $isMultipleWithGid = $dao->cgId
;
2477 return $isMultipleWithGid;