3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
37 * Business objects for managing custom data fields.
40 class CRM_Core_BAO_CustomField
extends CRM_Core_DAO_CustomField
{
43 * Array for valid combinations of data_type & descriptions
48 public static $_dataType = NULL;
51 * Array for valid combinations of data_type & html_type
56 public static $_dataToHtml = NULL;
59 * Array to hold (formatted) fields for import
64 public static $_importFields = NULL;
67 * Build and retrieve the list of data types and descriptions
71 * @return array Data type => Description
75 static function &dataType() {
76 if (!(self
::$_dataType)) {
77 self
::$_dataType = array(
78 'String' => ts('Alphanumeric'),
79 'Int' => ts('Integer'),
80 'Float' => ts('Number'),
81 'Money' => ts('Money'),
84 'Boolean' => ts('Yes or No'),
85 'StateProvince' => ts('State/Province'),
86 'Country' => ts('Country'),
89 'ContactReference' => ts('Contact Reference'),
92 return self
::$_dataType;
95 static function dataToHtml() {
96 if (!self
::$_dataToHtml) {
97 self
::$_dataToHtml = array(
99 'Text' => 'Text', 'Select' => 'Select',
100 'Radio' => 'Radio', 'CheckBox' => 'CheckBox',
101 'Multi-Select' => 'Multi-Select',
102 'AdvMulti-Select' => 'AdvMulti-Select',
103 'Autocomplete-Select' => 'Autocomplete-Select',
105 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
106 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
107 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
108 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
109 array('Date' => 'Select Date'),
110 array('Radio' => 'Radio'),
111 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
112 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
113 array('File' => 'File'),
114 array('Link' => 'Link'),
115 array('ContactReference' => 'Autocomplete-Select'),
118 return self
::$_dataToHtml;
122 * takes an associative array and creates a custom field object
124 * This function is invoked from within the web form layer and also from the api layer
126 * @param array $params (reference) an assoc array of name/value pairs
128 * @return object CRM_Core_DAO_CustomField object
132 static function create(&$params) {
133 if (!isset($params['id']) && !isset($params['column_name'])) {
134 // if add mode & column_name not present, calculate it.
135 $columnName = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
137 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
139 elseif (isset($params['id'])) {
140 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
147 //as during create if field is_searchable we had created index.
148 if (CRM_Utils_Array
::value('id', $params)) {
149 $indexExist = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
152 switch (CRM_Utils_Array
::value('html_type', $params)){
154 if(empty($params['date_format'])){
155 $config = CRM_Core_Config
::singleton();
156 $params['date_format'] = $config->dateInputFormat
;
160 case 'AdvMulti-Select':
162 if (isset($params['default_checkbox_option'])) {
163 $tempArray = array_keys($params['default_checkbox_option']);
164 $defaultArray = array();
165 foreach ($tempArray as $k => $v) {
166 if ($params['option_value'][$v]) {
167 $defaultArray[] = $params['option_value'][$v];
171 if (!empty($defaultArray)) {
172 // also add the seperator before and after the value per new conventio (CRM-1604)
173 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
177 if (CRM_Utils_Array
::value('default_option', $params)
178 && isset($params['option_value'][$params['default_option']])
180 $params['default_value'] = $params['option_value'][$params['default_option']];
186 $transaction = new CRM_Core_Transaction();
187 // create any option group & values if required
188 if ($params['html_type'] != 'Text' &&
189 in_array($params['data_type'], array(
190 'String', 'Int', 'Float', 'Money'))
193 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
194 $params['custom_group_id'],
199 if ($params['option_type'] == 1) {
200 // first create an option group for this custom group
201 $optionGroup = new CRM_Core_DAO_OptionGroup();
202 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
203 $optionGroup->title
= $params['label'];
204 $optionGroup->is_active
= 1;
205 $optionGroup->save();
206 $params['option_group_id'] = $optionGroup->id
;
207 if(!empty($params['option_value']) && is_array($params['option_value'])){
208 foreach ($params['option_value'] as $k => $v) {
209 if (strlen(trim($v))) {
210 $optionValue = new CRM_Core_DAO_OptionValue();
211 $optionValue->option_group_id
= $optionGroup->id
;
212 $optionValue->label
= $params['option_label'][$k];
213 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$k]);
214 switch ($params['data_type']) {
216 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($v);
220 $optionValue->value
= intval($v);
224 $optionValue->value
= floatval($v);
228 $optionValue->value
= trim($v);
231 $optionValue->weight
= $params['option_weight'][$k];
232 $optionValue->is_active
= CRM_Utils_Array
::value($k, $params['option_status'], FALSE);
233 $optionValue->save();
240 // check for orphan option groups
241 if (CRM_Utils_Array
::value('option_group_id', $params)) {
242 if (CRM_Utils_Array
::value('id', $params)) {
243 self
::fixOptionGroups($params['id'], $params['option_group_id']);
246 // if we dont have a default value
247 // retrive it from one of the other custom fields which use this option group
248 if (!CRM_Utils_Array
::value('default_value', $params)) {
249 //don't insert only value separator as default value, CRM-4579
250 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
254 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
257 $params['default_value'] = $defaultValue;
262 // since we need to save option group id :)
263 if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
264 $params['attributes'] = 'rows=4, cols=60';
267 $customField = new CRM_Core_DAO_CustomField();
268 $customField->copyValues($params);
269 $customField->is_required
= CRM_Utils_Array
::value('is_required', $params, FALSE);
270 $customField->is_searchable
= CRM_Utils_Array
::value('is_searchable', $params, FALSE);
271 $customField->is_search_range
= CRM_Utils_Array
::value('is_search_range', $params, FALSE);
272 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, FALSE);
273 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
274 $customField->save();
276 // make sure all values are present in the object for further processing
277 $customField->find(TRUE);
279 //create/drop the index when we toggle the is_searchable flag
280 if (CRM_Utils_Array
::value('id', $params)) {
281 self
::createField($customField, 'modify', $indexExist);
284 if (!isset($params['column_name'])) {
285 $columnName .= "_{$customField->id}";
287 $customField->column_name
= $columnName;
288 $customField->save();
289 // make sure all values are present in the object
290 $customField->find(TRUE);
292 self
::createField($customField, 'add');
295 // complete transaction
296 $transaction->commit();
298 CRM_Utils_System
::flushCache();
304 * Takes a bunch of params that are needed to match certain criteria and
305 * retrieves the relevant objects. Typically the valid params are only
306 * contact_id. We'll tweak this function to be more full featured over a period
307 * of time. This is the inverse function of create. It also stores all the retrieved
308 * values in the default array
310 * @param array $params (reference ) an assoc array of name/value pairs
311 * @param array $defaults (reference ) an assoc array to hold the flattened values
313 * @return object CRM_Core_DAO_CustomField object
317 static function retrieve(&$params, &$defaults) {
318 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
322 * update the is_active flag in the db
324 * @param int $id Id of the database record
325 * @param boolean $is_active Value we want to set the is_active field
327 * @return Object DAO object on sucess, null otherwise
332 static function setIsActive($id, $is_active) {
334 CRM_Utils_System
::flushCache();
336 //enable-disable CustomField
337 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
338 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
342 * Get the field title.
344 * @param int $id id of field.
346 * @return string name
352 public static function getTitle($id) {
353 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
357 * Store and return an array of all active custom fields.
359 * @param string $customDataType type of Custom Data
360 * @param boolean $showAll If true returns all fields (includes disabled fields)
361 * @param boolean $inline If true returns all inline fields (includes disabled fields)
362 * @param int $customDataSubType Custom Data sub type value
363 * @param int $customDataSubName Custom Data sub name value
364 * @param boolean $onlyParent return only top level custom data, for eg, only Participant and ignore subname and subtype
365 * @param boolean $onlySubType return only custom data for subtype
366 * @param boolean $checkPermission if false, do not include permissioning clause
368 * @return array $fields - an array of active custom fields.
373 public static function &getFields($customDataType = 'Individual',
376 $customDataSubType = NULL,
377 $customDataSubName = NULL,
379 $onlySubType = FALSE,
380 $checkPermission = TRUE
382 if ($customDataType &&
383 !is_array($customDataType)
386 if (in_array($customDataType,
387 CRM_Contact_BAO_ContactType
::subTypes()
389 // This is the case when getFieldsForImport() requires fields
390 // limited strictly to a subtype.
391 $customDataSubType = $customDataType;
392 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
396 if (in_array($customDataType,
397 array_keys(CRM_Core_SelectValues
::customGroupExtends())
399 // this makes the method flexible to support retrieving fields
400 // for multiple extends value.
401 $customDataType = array($customDataType);
405 if ($customDataSubType && !is_array($customDataSubType)) {
406 $customDataSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
407 trim($customDataSubType, CRM_Core_DAO
::VALUE_SEPARATOR
)
411 if (is_array($customDataType)) {
412 $cacheKey = implode('_', $customDataType);
415 $cacheKey = $customDataType;
418 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
419 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
420 $cacheKey .= $showAll ?
'_1' : '_0';
421 $cacheKey .= $inline ?
'_1_' : '_0_';
422 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
423 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
424 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
426 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
428 // also get the permission stuff here
429 if ($checkPermission) {
430 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
435 $permissionClause = '(1)';
438 // lets md5 permission clause and take first 8 characters
439 $cacheKey .= substr(md5($permissionClause), 0, 8);
441 if (strlen($cacheKey) > 40) {
442 $cacheKey = md5($cacheKey);
445 if (!self
::$_importFields ||
446 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
448 if (!self
::$_importFields) {
449 self
::$_importFields = array();
452 // check if we can retrieve from database cache
453 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
455 if ($fields === NULL) {
456 $cfTable = self
::getTableName();
459 if (is_array($customDataType)) {
461 foreach ($customDataType as $dataType) {
462 if (in_array($dataType,
463 array_keys(CRM_Core_SelectValues
::customGroupExtends())
465 if (in_array($dataType, array(
466 'Individual', 'Household', 'Organization'))) {
467 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
470 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
472 $value = $value ?
$value . ", {$val}" : $val;
476 $extends = "AND $cgTable.extends IN ( $value ) ";
481 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
484 $query = "SELECT $cfTable.id, $cfTable.label,
486 $cfTable.data_type, $cfTable.html_type,
487 $cfTable.options_per_line, $cfTable.text_length,
488 $cfTable.custom_group_id,
489 $cgTable.extends, $cfTable.is_search_range,
490 $cgTable.extends_entity_column_value,
491 $cgTable.extends_entity_column_id,
493 $cfTable.option_group_id,
494 $cfTable.date_format,
495 $cfTable.time_format,
499 ON $cfTable.custom_group_id = $cgTable.id
503 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
507 $query .= " AND $cgTable.style = 'Inline' ";
510 //get the custom fields for specific type in
511 //combination with fields those support any type.
512 if (!empty($customDataSubType)) {
513 $subtypeClause = array();
514 foreach ($customDataSubType as $subtype) {
515 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
516 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
519 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
521 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
524 if ($customDataSubName) {
525 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
528 // also get the permission stuff here
529 if ($checkPermission) {
530 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
535 $permissionClause = '(1)';
538 $query .= " $extends AND $permissionClause
539 ORDER BY $cgTable.weight, $cgTable.title,
540 $cfTable.weight, $cfTable.label";
542 $dao = CRM_Core_DAO
::executeQuery($query);
545 while (($dao->fetch()) != NULL) {
546 $fields[$dao->id
]['label'] = $dao->label
;
547 $fields[$dao->id
]['groupTitle'] = $dao->title
;
548 $fields[$dao->id
]['data_type'] = $dao->data_type
;
549 $fields[$dao->id
]['html_type'] = $dao->html_type
;
550 $fields[$dao->id
]['text_length'] = $dao->text_length
;
551 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
552 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
553 $fields[$dao->id
]['extends'] = $dao->extends;
554 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
555 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
556 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
557 $fields[$dao->id
]['is_view'] = $dao->is_view
;
558 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
559 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
560 $fields[$dao->id
]['date_format'] = $dao->date_format
;
561 $fields[$dao->id
]['time_format'] = $dao->time_format
;
564 CRM_Core_BAO_Cache
::setItem($fields,
566 "custom importableFields $cacheKey"
569 self
::$_importFields[$cacheKey] = $fields;
572 return self
::$_importFields[$cacheKey];
576 * Return the field ids and names (with groups) for import purpose.
578 * @param int $contactType Contact type
579 * @param boolean $showAll If true returns all fields (includes disabled fields)
580 * @param boolean $onlyParent return fields ONLY related to basic types
581 * @param boolean $search when called from search and multiple records need to be returned
582 * @param boolean $checkPermission if false, do not include permissioning clause
584 * @return array $fields -
589 public static function &getFieldsForImport($contactType = 'Individual',
593 $checkPermission = TRUE,
594 $withMultiple = FALSE
596 // Note: there are situations when we want getFieldsForImport() return fields related
597 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
598 $fields = &self
::getFields($contactType,
608 $importableFields = array();
609 foreach ($fields as $id => $values) {
610 // for now we should not allow multiple fields in profile / export etc, hence unsetting
612 (CRM_Utils_Array
::value('is_multiple', $values) && !$withMultiple)
617 /* generate the key for the fields array */
621 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
622 $importableFields[$key] = array(
624 'title' => CRM_Utils_Array
::value('label', $values),
625 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
627 'custom_field_id' => $id,
628 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
629 'data_type' => CRM_Utils_Array
::value('data_type', $values),
630 'html_type' => CRM_Utils_Array
::value('html_type', $values),
631 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
634 // CRM-6681, pass date and time format when html_type = Select Date
635 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
636 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
637 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
641 return $importableFields;
645 * Get the field id from an import key
647 * @param string $key The key to parse
649 * @return int|null The id (if exists)
653 public static function getKeyID($key, $all = FALSE) {
655 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
662 CRM_Utils_Array
::value(2, $match),
671 * Use the cache to get all values of a specific custom field
673 * @param int $fieldID the custom field ID
675 * @return object $field the field object
679 static function getFieldObject($fieldID) {
680 $field = new CRM_Core_DAO_CustomField();
682 // check if we can get the field values from the system cache
683 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
684 $cache = CRM_Utils_Cache
::singleton();
685 $fieldValues = $cache->get($cacheKey);
686 if (empty($fieldValues)) {
687 $field->id
= $fieldID;
688 if (!$field->find(TRUE)) {
689 CRM_Core_Error
::fatal();
692 $fieldValues = array();
693 CRM_Core_DAO
::storeValues($field, $fieldValues);
695 $cache->set($cacheKey, $fieldValues);
698 $field->copyValues($fieldValues);
705 * This function for building custom fields
707 * @param object $qf form object (reference)
708 * @param string $elementName name of the custom field
709 * @param boolean $inactiveNeeded
710 * @param boolean $userRequired true if required else false
711 * @param boolean $search true if used for search else false
712 * @param string $label label for custom field
717 public static function addQuickFormElement(&$qf,
720 $inactiveNeeded = FALSE,
725 // we use $_POST directly, since we dont want to use session memory, CRM-4677
726 if (isset($_POST['_qf_Relationship_refresh']) &&
727 ($_POST['_qf_Relationship_refresh'] == 'Search' ||
728 $_POST['_qf_Relationship_refresh'] == 'Search Again'
731 $useRequired = FALSE;
734 $field = self
::getFieldObject($fieldId);
736 // Fixed for Issue CRM-2183
737 if ($field->html_type
== 'TextArea' && $search) {
738 $field->html_type
= 'Text';
741 if (!isset($label)) {
742 $label = $field->label
;
746 * at some point in time we might want to split the below into small functions
749 switch ($field->html_type
) {
751 if ($field->is_search_range
&& $search) {
752 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
753 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
756 $element = &$qf->add(strtolower($field->html_type
), $elementName, $label,
758 $useRequired && !$search
765 if ($field->note_rows
) {
766 $attributes .= 'rows=' . $field->note_rows
;
769 $attributes .= 'rows=4';
771 if ($field->note_columns
) {
772 $attributes .= ' cols=' . $field->note_columns
;
775 $attributes .= ' cols=60';
777 if ($field->text_length
) {
778 $attributes .= ' maxlength=' . $field->text_length
;
780 $element = &$qf->add(strtolower($field->html_type
),
784 $useRequired && !$search
789 if ($field->is_search_range
&& $search) {
790 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
792 'format' => $field->date_format
,
793 'timeFormat' => $field->time_format
,
794 'startOffset' => $field->start_date_years
,
795 'endOffset' => $field->end_date_years
,
799 $qf->addDate($elementName . '_to', ts('To'), FALSE,
801 'format' => $field->date_format
,
802 'timeFormat' => $field->time_format
,
803 'startOffset' => $field->start_date_years
,
804 'endOffset' => $field->end_date_years
,
809 $required = $useRequired && !$search;
811 $qf->addDate($elementName, $label, $required, array(
812 'format' => $field->date_format
,
813 'timeFormat' => $field->time_format
,
814 'startOffset' => $field->start_date_years
,
815 'endOffset' => $field->end_date_years
,
822 if ($field->data_type
!= 'Boolean') {
823 $customOption = &CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
824 $field->option_group_id
826 foreach ($customOption as $v => $l) {
827 $choice[] = $qf->createElement('radio', NULL, '', $l, (string)$v, $field->attributes
);
829 $qf->addGroup($choice, $elementName, $label);
832 $choice[] = $qf->createElement('radio', NULL, '', ts('Yes'), '1', $field->attributes
);
833 $choice[] = $qf->createElement('radio', NULL, '', ts('No'), '0', $field->attributes
);
834 $qf->addGroup($choice, $elementName, $label);
836 if ($useRequired && !$search) {
837 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
842 $selectOption = &CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
843 $field->option_group_id
845 $qf->add('select', $elementName, $label,
847 '' => ts('- select -')) +
$selectOption,
848 $useRequired && !$search
852 //added for select multiple
854 case 'AdvMulti-Select':
855 $selectOption = &CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
856 $field->option_group_id
859 count($selectOption) > 1
861 $selectOption['CiviCRM_OP_OR'] = ts('Select to match ANY; unselect to match ALL');
864 $include =& $qf->addElement(
867 $label, $selectOption,
871 'class' => 'advmultiselect',
875 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
876 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
878 if ($useRequired && !$search) {
879 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
884 $selectOption = &CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
885 $field->option_group_id
888 count($selectOption) > 1
890 $selectOption['CiviCRM_OP_OR'] = ts('Select to match ANY; unselect to match ALL');
892 $qf->addElement('select', $elementName, $label, $selectOption, array('size' => '5', 'multiple'));
894 if ($useRequired && !$search) {
895 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
900 $customOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
901 $field->option_group_id
904 foreach ($customOption as $v => $l) {
905 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l);
910 $check[] = &$qf->addElement('advcheckbox', 'CiviCRM_OP_OR', NULL, ts('Check to match ANY; uncheck to match ALL'));
912 $qf->addGroup($check, $elementName, $label);
913 if ($useRequired && !$search) {
914 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
919 // we should not build upload file in search mode
924 strtolower($field->html_type
),
928 $useRequired && !$search
930 $qf->addUploadElement($elementName);
933 case 'Select State/Province':
935 $stateOption = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::stateProvince();
936 $qf->add('select', $elementName, $label, $stateOption,
937 $useRequired && !$search
941 case 'Multi-Select State/Province':
942 //Add Multi-select State/Province
943 $stateOption = CRM_Core_PseudoConstant
::stateProvince();
945 $qf->addElement('select', $elementName, $label, $stateOption, array('size' => '5', 'multiple'));
946 if ($useRequired && !$search) {
947 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
951 case 'Select Country':
953 $countryOption = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::country();
954 $qf->add('select', $elementName, $label, $countryOption,
955 $useRequired && !$search
959 case 'Multi-Select Country':
961 $countryOption = CRM_Core_PseudoConstant
::country();
962 $qf->addElement('select', $elementName, $label, $countryOption, array('size' => '5', 'multiple'));
963 if ($useRequired && !$search) {
964 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
968 case 'RichTextEditor':
969 $attributes = array('rows' => $field->note_rows
, 'cols' => $field->note_columns
);
970 if ($field->text_length
) {
971 $attributes['maxlength'] = $field->text_length
;
973 $qf->addWysiwyg($elementName, $label, $attributes, $search);
976 case 'Autocomplete-Select':
977 $qf->add('text', $elementName, $label, $field->attributes
,
978 $useRequired && !$search
981 $hiddenEleName = $elementName . '_id';
982 if (substr($elementName, -1) == ']') {
983 $hiddenEleName = substr($elementName, 0, -1) . '_id]';
985 $qf->addElement('hidden', $hiddenEleName, '', array('id' => str_replace(array(']', '['), array('', '_'), $hiddenEleName)));
987 static $customUrls = array();
988 if ($field->data_type
== 'ContactReference') {
989 //$urlParams = "className=CRM_Contact_Page_AJAX&fnName=getContactList&json=1&reset=1&context=customfield&id={$field->id}";
990 $urlParams = "context=customfield&id={$field->id}";
992 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
997 $actualElementValue = $qf->getSubmitValue($hiddenEleName);
998 $qf->addRule($elementName, ts('Select a valid contact for %1.', array(1 => $label)), 'validContact', $actualElementValue);
1001 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/auto',
1002 "reset=1&ogid={$field->option_group_id}&cfid={$field->id}",
1005 $qf->addRule($elementName, ts('Select a valid value for %1.', array(1 => $label)),
1006 'autocomplete', array(
1007 'fieldID' => $field->id
,
1008 'optionGroupID' => $field->option_group_id
,
1013 $qf->assign('customUrls', $customUrls);
1017 switch ($field->data_type
) {
1019 // integers will have numeric rule applied to them.
1020 if ($field->is_search_range
&& $search) {
1021 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1022 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1025 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1030 if ($field->is_search_range
&& $search) {
1031 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1032 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1035 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1040 if ($field->is_search_range
&& $search) {
1041 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1042 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1045 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1055 'onfocus' => "if (!this.value) { this.value='http://';} else return false",
1056 'onblur' => "if ( this.value == 'http://') { this.value='';} else return false",
1058 $useRequired && !$search
1060 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1063 if ($field->is_view
&& !$search) {
1064 $qf->freeze($elementName);
1069 * Delete the Custom Field.
1071 * @param object $field - the field object
1079 public static function deleteField($field) {
1080 CRM_Utils_System
::flushCache();
1082 // first delete the custom option group and values associated with this field
1083 if ($field->option_group_id
) {
1084 //check if option group is related to any other field, if
1085 //not delete the option group and related option values
1086 self
::checkOptionGroup($field->option_group_id
);
1089 // next drop the column from the custom value table
1090 self
::createField($field, 'delete');
1093 CRM_Core_BAO_UFField
::delUFField($field->id
);
1094 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1100 * Given a custom field value, its id and the set of options
1101 * find the display value for this field
1103 * @param mixed $value the custom field value
1104 * @param int $id the custom field id
1105 * @param int $options the assoc array of option name/value pairs
1107 * @return string the display value
1112 static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1113 $option = &$options[$id];
1114 $attributes = &$option['attributes'];
1115 $html_type = $attributes['html_type'];
1116 $data_type = $attributes['data_type'];
1117 $format = CRM_Utils_Array
::value('format', $attributes);
1119 return self
::getDisplayValueCommon($value,
1129 static function getDisplayValueCommon($value,
1140 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1141 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1142 $html_type == 'Select' ||
1143 $html_type == 'CheckBox' ||
1144 $html_type == 'AdvMulti-Select' ||
1145 $html_type == 'Multi-Select'
1148 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1151 switch ($html_type) {
1153 if ($data_type == 'Boolean') {
1154 $display = $value ?
ts('Yes') : ts('No');
1157 $display = CRM_Utils_Array
::value($value, $option);
1161 case 'Autocomplete-Select':
1162 if ($data_type == 'ContactReference' &&
1165 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1168 $display = CRM_Utils_Array
::value($value, $option);
1173 $display = CRM_Utils_Array
::value($value, $option);
1177 case 'AdvMulti-Select':
1178 case 'Multi-Select':
1179 if (is_array($value)) {
1180 $checkedData = $value;
1183 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1184 substr($value, 1, -1)
1186 if ($html_type == 'CheckBox') {
1188 foreach ($checkedData as $v) {
1191 $checkedData = $newData;
1197 foreach ($checkedData as $key => $val) {
1198 if ($key === 'CiviCRM_OP_OR') {
1202 if ($html_type == 'CheckBox') {
1205 $v[] = CRM_Utils_Array
::value($key, $option);
1210 $v[] = CRM_Utils_Array
::value($val, $option);
1214 $display = implode(', ', $v);
1219 if (is_array($value)) {
1220 foreach ($value as $key => $val) {
1221 $display[$key] = CRM_Utils_Date
::customFormat($val);
1225 // remove time element display if time is not set
1226 if (empty($option['attributes']['time_format'])) {
1227 $value = substr($value, 0, 10);
1229 $display = CRM_Utils_Date
::customFormat($value);
1233 case 'Select State/Province':
1234 if (empty($value)) {
1238 $display = CRM_Core_PseudoConstant
::stateProvince($value);
1242 case 'Multi-Select State/Province':
1243 if (is_array($value)) {
1244 $checkedData = $value;
1247 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1248 substr($value, 1, -1)
1252 $states = CRM_Core_PseudoConstant
::stateProvince();
1254 foreach ($checkedData as $stateID) {
1258 $display .= $states[$stateID];
1262 case 'Select Country':
1263 if (empty($value)) {
1267 $display = CRM_Core_PseudoConstant
::country($value);
1271 case 'Multi-Select Country':
1272 if (is_array($value)) {
1273 $checkedData = $value;
1276 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1277 substr($value, 1, -1)
1281 $countries = CRM_Core_PseudoConstant
::country();
1283 foreach ($checkedData as $countryID) {
1287 $display .= $countries[$countryID];
1293 $url = self
::getFileURL($contactID, $fieldID, $value);
1295 $display = $url['file_url'];
1301 if (empty($value)) {
1305 $display = nl2br($value);
1310 if (empty($value)) {
1318 return $display ?
$display : $value;
1322 * Function to set default values for custom data used in profile
1324 * @params int $customFieldId custom field id
1325 * @params string $elementName custom field name
1326 * @params array $defaults associated array of fields
1327 * @params int $contactId contact id
1328 * @param int $mode profile mode
1329 * @param mixed $value if passed - dont fetch value from db,
1330 * just format the given value
1334 static function setProfileDefaults($customFieldId,
1341 //get the type of custom field
1342 $customField = new CRM_Core_BAO_CustomField();
1343 $customField->id
= $customFieldId;
1344 $customField->find(TRUE);
1347 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1348 $value = $customField->default_value
;
1352 if (!isset($value)) {
1353 $info = self
::getTableColumnGroup($customFieldId);
1354 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1355 $result = CRM_Core_DAO
::executeQuery($query);
1356 if ($result->fetch()) {
1357 $value = $result->value
;
1361 if ($customField->data_type
== 'Country') {
1363 $config = CRM_Core_Config
::singleton();
1364 if ($config->defaultContactCountry
) {
1365 $value = $config->defaultContactCountry();
1371 //set defaults if mode is registration
1372 if (!trim($value) &&
1374 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1376 $value = $customField->default_value
;
1379 if ($customField->data_type
== 'Money' && isset($value)) {
1380 $value = number_format($value, 2);
1382 switch ($customField->html_type
) {
1384 case 'AdvMulti-Select':
1385 case 'Multi-Select':
1386 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1387 $defaults[$elementName] = array();
1388 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1389 substr($value, 1, -1)
1391 foreach ($customOption as $val) {
1392 if (in_array($val['value'], $checkedValue)) {
1393 if ($customField->html_type
== 'CheckBox') {
1394 $defaults[$elementName][$val['value']] = 1;
1396 elseif ($customField->html_type
== 'Multi-Select' ||
1397 $customField->html_type
== 'AdvMulti-Select'
1399 $defaults[$elementName][$val['value']] = $val['value'];
1407 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1410 $customField->date_format
,
1411 $customField->time_format
1416 case 'Autocomplete-Select':
1417 if ($customField->data_type
== 'ContactReference') {
1418 if (is_numeric($value)) {
1419 $defaults[$elementName . '_id'] = $value;
1420 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1424 $label = CRM_Core_BAO_CustomOption
::getOptionLabel($customField->id
, $value);
1425 $defaults[$elementName . '_id'] = $value;
1426 $defaults[$elementName] = $label;
1431 $defaults[$elementName] = $value;
1435 static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE) {
1438 $params = array('id' => $cfID);
1439 $defaults = array();
1440 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1441 $columnName = $defaults['column_name'];
1443 //table name of custom data
1444 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1445 $defaults['custom_group_id'],
1449 //query to fetch id from civicrm_file
1450 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1451 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1456 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1461 $result['file_id'] = $fileID;
1463 if ($fileType == 'image/jpeg' ||
1464 $fileType == 'image/pjpeg' ||
1465 $fileType == 'image/gif' ||
1466 $fileType == 'image/x-png' ||
1467 $fileType == 'image/png'
1469 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1474 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1475 list($imageWidth, $imageHeight) = getimagesize($path);
1476 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1477 $url = CRM_Utils_System
::url('civicrm/file',
1478 "reset=1&id=$fileID&eid=$contactID",
1479 $absolute, NULL, TRUE, TRUE
1481 $result['file_url'] = "<a href='javascript:imagePopUp(\"$url\");'><img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/></a>";
1482 // for non image files
1485 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1489 $url = CRM_Utils_System
::url('civicrm/file',
1490 "reset=1&id=$fileID&eid=$contactID",
1491 $absolute, NULL, TRUE, TRUE
1493 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1501 * Format custom fields before inserting
1503 * @param int $customFieldId custom field id
1504 * @param array $customFormatted formatted array
1505 * @param mix $value value of custom field
1506 * @param string $customFieldExtend custom field extends
1507 * @param int $customValueId custom option value id
1508 * @param int $entityId entity id (contribution, membership...)
1509 * @param boolean $inline consider inline custom groups only
1510 * @param boolean $checkPermission if false, do not include permissioning clause
1512 * @return array $customFormatted formatted custom field array
1515 static function formatCustomField($customFieldId, &$customFormatted, $value,
1516 $customFieldExtend, $customValueId = NULL,
1519 $checkPermission = TRUE
1521 //get the custom fields for the entity
1522 //subtype and basic type
1523 $customDataSubType = NULL;
1524 if (in_array($customFieldExtend,
1525 CRM_Contact_BAO_ContactType
::subTypes()
1527 // This is the case when getFieldsForImport() requires fields
1528 // of subtype and its parent.CRM-5143
1529 $customDataSubType = $customFieldExtend;
1530 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1533 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1543 if (!array_key_exists($customFieldId, $customFields)) {
1547 // return if field is a 'code' field
1548 if (CRM_Utils_Array
::value('is_view', $customFields[$customFieldId])) {
1552 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1554 if (is_array($customFieldExtend)) {
1555 $customFieldExtend = $customFieldExtend[0];
1557 if (!$customValueId &&
1558 // we always create new entites for is_multiple unless specified
1559 !$customFields[$customFieldId]['is_multiple'] &&
1565 WHERE entity_id={$entityId}";
1567 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1570 //fix checkbox, now check box always submits values
1571 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1573 // Note that only during merge this is not an array, and you can directly use value
1574 if (is_array($value)) {
1575 $selectedValues = array();
1576 foreach ($value as $selId => $val) {
1578 $selectedValues[] = $selId;
1581 if (!empty($selectedValues)) {
1582 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1584 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1593 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1594 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1597 // Note that only during merge this is not an array,
1598 // and you can directly use value, CRM-4385
1599 if (is_array($value)) {
1600 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1601 array_values($value)
1602 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1610 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1611 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1612 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1614 $customFields[$customFieldId]['data_type'] == 'String' &&
1615 !empty($customFields[$customFieldId]['text_length']) &&
1618 // lets make sure that value is less than the length, else we'll
1619 // be losing some data, CRM-7481
1620 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1621 // need to do a few things here
1623 // 1. lets find a new length
1624 $newLength = $customFields[$customFieldId]['text_length'];
1625 $minLength = strlen($value);
1626 while ($newLength < $minLength) {
1627 $newLength = $newLength * 2;
1630 // set the custom field meta data to have a length larger than value
1631 // alter the custom value table column to match this length
1632 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1637 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1638 if (!CRM_Utils_System
::isNull($value)) {
1639 $format = $customFields[$customFieldId]['date_format'];
1640 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1645 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1646 $customFields[$customFieldId]['data_type'] == 'Money'
1652 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1653 $value = CRM_Utils_Rule
::cleanMoney($value);
1657 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1658 $customFields[$customFieldId]['data_type'] == 'Country'
1668 if ($customFields[$customFieldId]['data_type'] == 'File') {
1669 if (empty($value)) {
1673 $config = CRM_Core_Config
::singleton();
1675 $fName = $value['name'];
1676 $mimeType = $value['type'];
1678 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1680 // rename this file to go into the secure directory
1681 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1682 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1686 if ($customValueId) {
1691 $params = array(1 => array($customValueId, 'Integer'));
1692 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1695 $fileDAO = new CRM_Core_DAO_File();
1698 $fileDAO->id
= $fileId;
1701 $fileDAO->uri
= $filename;
1702 $fileDAO->mime_type
= $mimeType;
1703 $fileDAO->upload_date
= date('Ymdhis');
1705 $fileId = $fileDAO->id
;
1709 if (!is_array($customFormatted)) {
1710 $customFormatted = array();
1713 if (!array_key_exists($customFieldId, $customFormatted)) {
1714 $customFormatted[$customFieldId] = array();
1718 if ($customValueId) {
1719 $index = $customValueId;
1722 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1723 $customFormatted[$customFieldId][$index] = array();
1725 $customFormatted[$customFieldId][$index] = array(
1726 'id' => $customValueId > 0 ?
$customValueId : NULL,
1728 'type' => $customFields[$customFieldId]['data_type'],
1729 'custom_field_id' => $customFieldId,
1730 'custom_group_id' => $groupID,
1731 'table_name' => $tableName,
1732 'column_name' => $columnName,
1733 'file_id' => $fileId,
1734 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1737 //we need to sort so that custom fields are created in the order of entry
1738 krsort($customFormatted[$customFieldId]);
1739 return $customFormatted;
1742 static function &defaultCustomTableSchema(&$params) {
1743 // add the id and extends_id
1745 'name' => $params['name'],
1746 'is_multiple' => $params['is_multiple'],
1747 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1751 'type' => 'int unsigned',
1754 'attributes' => 'AUTO_INCREMENT',
1755 'comment' => 'Default MySQL primary key',
1758 'name' => 'entity_id',
1759 'type' => 'int unsigned',
1761 'comment' => 'Table that this extends',
1762 'fk_table_name' => $params['extends_name'],
1763 'fk_field_name' => 'id',
1764 'fk_attributes' => 'ON DELETE CASCADE',
1769 if (!$params['is_multiple']) {
1770 $table['indexes'] = array(
1773 'field_name_1' => 'entity_id',
1780 static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1781 $tableName = CRM_Core_DAO
::getFieldValue(
1782 'CRM_Core_DAO_CustomGroup',
1783 $field->custom_group_id
,
1788 'table_name' => $tableName,
1789 'operation' => $operation,
1790 'name' => $field->column_name
,
1791 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1795 'required' => $field->is_required
,
1796 'searchable' => $field->is_searchable
,
1799 if ($operation == 'delete') {
1800 $fkName = "{$tableName}_{$field->column_name}";
1801 if (strlen($fkName) >= 48) {
1802 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1804 $params['fkName'] = $fkName;
1806 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1807 $params['fk_table_name'] = 'civicrm_country';
1808 $params['fk_field_name'] = 'id';
1809 $params['fk_attributes'] = 'ON DELETE SET NULL';
1811 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1812 $params['type'] = 'varchar(255)';
1814 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1815 $params['fk_table_name'] = 'civicrm_state_province';
1816 $params['fk_field_name'] = 'id';
1817 $params['fk_attributes'] = 'ON DELETE SET NULL';
1819 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1820 $params['type'] = 'varchar(255)';
1822 elseif ($field->data_type
== 'File') {
1823 $params['fk_table_name'] = 'civicrm_file';
1824 $params['fk_field_name'] = 'id';
1825 $params['fk_attributes'] = 'ON DELETE SET NULL';
1827 elseif ($field->data_type
== 'ContactReference') {
1828 $params['fk_table_name'] = 'civicrm_contact';
1829 $params['fk_field_name'] = 'id';
1830 $params['fk_attributes'] = 'ON DELETE SET NULL';
1832 if ($field->default_value
) {
1833 $params['default'] = "'{$field->default_value}'";
1836 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1840 * Determine whether it would be safe to move a field
1842 * @param int $fieldID FK to civicrm_custom_field
1843 * @param int $newGroupID FK to civicrm_custom_group
1848 static function _moveFieldValidate($fieldID, $newGroupID) {
1851 $field = new CRM_Core_DAO_CustomField();
1852 $field->id
= $fieldID;
1853 if (!$field->find(TRUE)) {
1854 $errors['fieldID'] = 'Invalid ID for custom field';
1858 $oldGroup = new CRM_Core_DAO_CustomGroup();
1859 $oldGroup->id
= $field->custom_group_id
;
1860 if (!$oldGroup->find(TRUE)) {
1861 $errors['fieldID'] = 'Invalid ID for old custom group';
1865 $newGroup = new CRM_Core_DAO_CustomGroup();
1866 $newGroup->id
= $newGroupID;
1867 if (!$newGroup->find(TRUE)) {
1868 $errors['newGroupID'] = 'Invalid ID for new custom group';
1874 FROM civicrm_custom_field a
1875 INNER JOIN civicrm_custom_field b
1877 AND a.label = b.label
1878 AND b.custom_group_id = %2
1881 1 => array($field->id
, 'Integer'),
1882 2 => array($newGroup->id
, 'Integer'),
1884 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1886 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1889 $tableName = $oldGroup->table_name
;
1890 $columnName = $field->column_name
;
1895 WHERE $columnName is not null
1897 $count = CRM_Core_DAO
::singleValueQuery($query,
1898 CRM_Core_DAO
::$_nullArray
1903 FROM civicrm_custom_group
1904 WHERE id IN ( %1, %2 )
1906 $params = array(1 => array($oldGroup->id
, 'Integer'),
1907 2 => array($newGroup->id
, 'Integer'),
1910 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1912 while ($dao->fetch()) {
1913 $extends[] = $dao->extends;
1915 if ($extends[0] != $extends[1]) {
1916 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1920 return empty($errors) ?
TRUE : $errors;
1924 * Move a custom data field from one group (table) to another
1926 * @param int $fieldID FK to civicrm_custom_field
1927 * @param int $newGroupID FK to civicrm_custom_group
1931 static function moveField($fieldID, $newGroupID) {
1932 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1933 if (TRUE !== $validation) {
1934 CRM_Core_Error
::fatal(implode(' ', $validation));
1936 $field = new CRM_Core_DAO_CustomField();
1937 $field->id
= $fieldID;
1940 $newGroup = new CRM_Core_DAO_CustomGroup();
1941 $newGroup->id
= $newGroupID;
1942 $newGroup->find(TRUE);
1944 $oldGroup = new CRM_Core_DAO_CustomGroup();
1945 $oldGroup->id
= $field->custom_group_id
;
1946 $oldGroup->find(TRUE);
1949 $add->custom_group_id
= $newGroup->id
;
1950 self
::createField($add, 'add');
1952 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1953 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1954 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1956 CRM_Core_DAO
::executeQuery($sql);
1959 $del->custom_group_id
= $oldGroup->id
;
1960 self
::createField($del, 'delete');
1964 CRM_Utils_System
::flushCache();
1968 * Get the database table name and column name for a custom field
1970 * @param int $fieldID - the fieldID of the custom field
1971 * @param boolean $force - force the sql to be run again (primarily used for tests)
1973 * @return array - fatal is fieldID does not exists, else array of tableName, columnName
1977 static function getTableColumnGroup($fieldID, $force = FALSE) {
1978 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
1979 $cache = CRM_Utils_Cache
::singleton();
1980 $fieldValues = $cache->get($cacheKey);
1981 if (empty($fieldValues) ||
$force) {
1983 SELECT cg.table_name, cf.column_name, cg.id
1984 FROM civicrm_custom_group cg,
1985 civicrm_custom_field cf
1986 WHERE cf.custom_group_id = cg.id
1988 $params = array(1 => array($fieldID, 'Integer'));
1989 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1991 if (!$dao->fetch()) {
1992 CRM_Core_Error
::fatal();
1995 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
1996 $cache->set($cacheKey, $fieldValues);
1998 return $fieldValues;
2002 * Function to get custom option groups
2004 * @params array $includeFieldIds ids of custom fields for which
2005 * option groups must be included.
2007 * Currently this is required in the cases where option groups are to be included
2008 * for inactive fields : CRM-5369
2012 * @return $customOptionGroup
2015 public static function &customOptionGroup($includeFieldIds = NULL) {
2016 static $customOptionGroup = NULL;
2018 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2019 if ($cacheKey == 'force') {
2020 $customOptionGroup[$cacheKey] = NULL;
2023 if (!CRM_Utils_Array
::value($cacheKey, $customOptionGroup)) {
2024 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2026 //support for single as well as array format.
2027 if (!empty($includeFieldIds)) {
2028 if (is_array($includeFieldIds)) {
2029 $includeFieldIds = implode(',', $includeFieldIds);
2031 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2035 SELECT g.id, g.title
2036 FROM civicrm_option_group g
2037 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2038 WHERE {$whereClause}";
2040 $dao = CRM_Core_DAO
::executeQuery($query);
2041 while ($dao->fetch()) {
2042 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2046 return $customOptionGroup[$cacheKey];
2050 * Function to fix orphan groups
2052 * @params int $customFieldId custom field id
2053 * @params int $optionGroupId option group id
2060 static function fixOptionGroups($customFieldId, $optionGroupId) {
2061 // check if option group belongs to any custom Field else delete
2062 // get the current option group
2063 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2067 // get the updated option group
2068 // if both are same return
2069 if ($currentOptionGroupId == $optionGroupId) {
2073 // check if option group is related to any other field
2074 self
::checkOptionGroup($currentOptionGroupId);
2078 * Function to check if option group is related to more than one
2081 * @params int $optionGroupId option group id
2086 static function checkOptionGroup($optionGroupId) {
2089 FROM civicrm_custom_field
2090 WHERE option_group_id = {$optionGroupId}";
2092 $count = CRM_Core_DAO
::singleValueQuery($query);
2095 //delete the option group
2096 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2100 static function getOptionGroupDefault($optionGroupId, $htmlType) {
2102 SELECT default_value, html_type
2103 FROM civicrm_custom_field
2104 WHERE option_group_id = {$optionGroupId}
2105 AND default_value IS NOT NULL
2106 ORDER BY html_type";
2108 $dao = CRM_Core_DAO
::executeQuery($query);
2109 $defaultValue = NULL;
2110 $defaultHTMLType = NULL;
2111 while ($dao->fetch()) {
2112 if ($dao->html_type
== $htmlType) {
2113 return $dao->default_value
;
2115 if ($defaultValue == NULL) {
2116 $defaultValue = $dao->default_value
;
2117 $defaultHTMLType = $dao->html_type
;
2121 // some conversions are needed if either the old or new has a html type which has potential
2122 // multiple default values.
2123 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2124 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2126 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2128 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2129 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2131 $defaultValue = substr($defaultValue, 1, -1);
2132 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2133 substr($defaultValue, 1, -1)
2135 $defaultValue = $values[0];
2138 return $defaultValue;
2141 static function postProcess(&$params,
2144 $customFieldExtends,
2147 $customData = array();
2149 foreach ($params as $key => $value) {
2150 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2152 // for autocomplete transfer hidden value instead of label
2153 if ($params[$key] && isset($params[$key . '_id'])) {
2154 $value = $params[$key . '_id'];
2157 // we need to append time with date
2158 if ($params[$key] && isset($params[$key . '_time'])) {
2159 $value .= ' ' . $params[$key . '_time'];
2162 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2165 $customFieldExtends,
2166 $customFieldInfo[1],
2175 static function buildOption($field, &$options) {
2176 // Fixme - adding anything but options to the $options array is a bad idea
2177 // What if an option had the key 'attributes'?
2178 $options['attributes'] = array(
2179 'label' => $field['label'],
2180 'data_type' => $field['data_type'],
2181 'html_type' => $field['html_type'],
2184 $optionGroupID = NULL;
2185 if (($field['html_type'] == 'CheckBox' ||
2186 $field['html_type'] == 'Radio' ||
2187 $field['html_type'] == 'Select' ||
2188 $field['html_type'] == 'AdvMulti-Select' ||
2189 $field['html_type'] == 'Multi-Select' ||
2190 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2192 if ($field['option_group_id']) {
2193 $optionGroupID = $field['option_group_id'];
2195 elseif ($field['data_type'] != 'Boolean') {
2196 CRM_Core_Error
::fatal();
2200 // build the cache for custom values with options (label => value)
2201 if ($optionGroupID != NULL) {
2204 FROM civicrm_option_value
2205 WHERE option_group_id = $optionGroupID
2208 $dao = CRM_Core_DAO
::executeQuery($query);
2209 while ($dao->fetch()) {
2210 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2211 $num = round($dao->value
, 2);
2212 $options["$num"] = $dao->label
;
2215 $options[$dao->value
] = $dao->label
;
2219 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2223 static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2224 $params = array(1 => array($fieldLabel, 'String'));
2226 $params[2] = array($groupTitle, 'String');
2229 FROM civicrm_custom_field f
2230 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2231 WHERE ( f.label = %1 OR f.name = %1 )
2232 AND ( g.title = %2 OR g.name = %2 )
2238 FROM civicrm_custom_field f
2239 WHERE ( f.label = %1 OR f.name = %1 )
2243 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2244 if ($dao->fetch() &&
2255 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2258 static function getNameFromID($ids) {
2259 if (is_array($ids)) {
2260 $ids = implode(',', $ids);
2263 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2264 FROM civicrm_custom_field f
2265 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2266 WHERE f.id IN ($ids)";
2269 $dao = CRM_Core_DAO
::executeQuery($sql);
2271 while ($dao->fetch()) {
2272 $result[$dao->id
] = array(
2273 'field_name' => $dao->field_name
,
2274 'field_label' => $dao->field_label
,
2275 'group_name' => $dao->group_name
,
2276 'group_title' => $dao->group_title
,
2283 * Validate custom data.
2285 * @param array $params custom data submitted.
2286 * ie array( 'custom_1' => 'validate me' );
2288 * @return array $errors validation errors.
2291 static function validateCustomData($params) {
2293 if (!is_array($params) ||
empty($params)) {
2298 //pick up profile fields.
2299 $profileFields = array();
2300 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2302 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2304 CRM_Core_Action
::VIEW
2308 //lets start w/ params.
2309 foreach ($params as $key => $value) {
2310 $customFieldID = self
::getKeyID($key);
2311 if (!$customFieldID) {
2315 //load the structural info for given field.
2316 $field = new CRM_Core_DAO_CustomField();
2317 $field->id
= $customFieldID;
2318 if (!$field->find(TRUE)) {
2321 $dataType = $field->data_type
;
2323 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2324 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2325 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2327 $fieldTitle = $field->label
;
2330 //no need to validate.
2331 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2335 //lets validate first for required field.
2336 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2337 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2341 //now time to take care of custom field form rules.
2342 $ruleName = $errorMsg = NULL;
2343 switch ($dataType) {
2345 $ruleName = 'integer';
2346 $errorMsg = ts('%1 must be an integer (whole number).',
2347 array(1 => $fieldTitle)
2352 $ruleName = 'money';
2353 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2354 array(1 => $fieldTitle)
2359 $ruleName = 'numeric';
2360 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2361 array(1 => $fieldTitle)
2366 $ruleName = 'wikiURL';
2367 $errorMsg = ts('%1 must be valid Website.',
2368 array(1 => $fieldTitle)
2373 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2375 $funName = "CRM_Utils_Rule::{$ruleName}";
2376 if (is_callable($funName)) {
2377 $valid = call_user_func($funName, $value);
2380 $errors[$key] = $errorMsg;
2388 static function isMultiRecordField($customId) {
2389 $isMultipleWithGid = FALSE;
2390 if (!is_numeric($customId)) {
2391 $customId = self
::getKeyID($customId);
2393 if (is_numeric($customId)) {
2394 $sql = "SELECT cg.id cgId
2395 FROM civicrm_custom_group cg
2396 INNER JOIN civicrm_custom_field cf
2397 ON cg.id = cf.custom_group_id
2398 WHERE cf.id = %1 AND cg.is_multiple = 1";
2399 $params[1] = array($customId, 'Integer');
2400 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2401 if ($dao->fetch()) {
2403 $isMultipleWithGid = $dao->cgId
;
2408 return $isMultipleWithGid;