Skip to content

Commit

Permalink
Merge pull request #12218 from mattwire/getcustomfieldid
Browse files Browse the repository at this point in the history
dev/core#144 getCustomFieldID switch to API, add caching, add full string return option
  • Loading branch information
eileenmcnaughton authored Jun 15, 2018
2 parents ef444b4 + b906acc commit 36a26e2
Showing 1 changed file with 33 additions and 34 deletions.
67 changes: 33 additions & 34 deletions CRM/Core/BAO/CustomField.php
Original file line number Diff line number Diff line change
Expand Up @@ -2189,46 +2189,45 @@ public static function postProcess(
}

/**
* Get custom field ID from field/group name/title.
*
*/

/**
* Get custom field ID.
* @param string $fieldName Field name or label
* @param string|null $groupTitle (Optional) Group name or label
* @param bool $fullString Whether to return "custom_123" or "123"
*
* @param string $fieldLabel
* @param null $groupTitle
*
* @return int|null
* @return string|int|null
* @throws \CiviCRM_API3_Exception
*/
public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
$params = array(1 => array($fieldLabel, 'String'));
if ($groupTitle) {
$params[2] = array($groupTitle, 'String');
$sql = "
SELECT f.id
FROM civicrm_custom_field f
INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
WHERE ( f.label = %1 OR f.name = %1 )
AND ( g.title = %2 OR g.name = %2 )
";
}
else {
$sql = "
SELECT f.id
FROM civicrm_custom_field f
WHERE ( f.label = %1 OR f.name = %1 )
";
}
public static function getCustomFieldID($fieldName, $groupTitle = NULL, $fullString = FALSE) {
if (!isset(Civi::$statics['CRM_Core_BAO_CustomField'][$fieldName])) {
$customFieldParams = [
'name' => $fieldName,
'label' => $fieldName,
'options' => ['or' => [["name", "label"]]],
];

if ($groupTitle) {
$customFieldParams['custom_group_id.name'] = $groupTitle;
$customFieldParams['custom_group_id.title'] = $groupTitle;
$customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
}

$dao = CRM_Core_DAO::executeQuery($sql, $params);
if ($dao->fetch() &&
$dao->N == 1
) {
return $dao->id;
$field = civicrm_api3('CustomField', 'get', $customFieldParams);

if (empty($field['id'])) {
Civi::$statics['CRM_Core_BAO_CustomField'][$fieldName]['id'] = NULL;
Civi::$statics['CRM_Core_BAO_CustomField'][$fieldName]['string'] = NULL;
}
else {
Civi::$statics['CRM_Core_BAO_CustomField'][$fieldName]['id'] = $field['id'];
Civi::$statics['CRM_Core_BAO_CustomField'][$fieldName]['string'] = 'custom_' . $field['id'];
}
}
else {
return NULL;

if ($fullString) {
return Civi::$statics['CRM_Core_BAO_CustomField'][$fieldName]['string'];
}
return Civi::$statics['CRM_Core_BAO_CustomField'][$fieldName]['id'];
}

/**
Expand Down

0 comments on commit 36a26e2

Please sign in to comment.