3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Core_BAO_OptionValue
extends CRM_Core_DAO_OptionValue
{
20 * Create option value.
22 * Note that the create function calls 'add' but has more business logic.
24 * @param array $params
27 * @return CRM_Core_DAO_OptionValue
28 * @throws \CRM_Core_Exception
30 public static function create($params) {
31 if (empty($params['id'])) {
32 self
::setDefaults($params);
34 return CRM_Core_BAO_OptionValue
::add($params);
38 * Set default Parameters.
39 * This functions sets default parameters if not set:
40 * - name & label are set to each other as required (it might make more sense for one
41 * to be required but this would mean a change to the api level)
42 * - weight & value will be set to their respective option groups next values
43 * if nothing is passed in.
45 * Note this function does not check for presence of $params['id'] so should only be called
46 * if 'id' is not present
48 * @param array $params
50 public static function setDefaults(&$params) {
51 $params['label'] = $params['label'] ??
$params['name'];
52 $params['name'] = $params['name'] ?? CRM_Utils_String
::titleToVar($params['label']);
53 $params['weight'] = $params['weight'] ?? self
::getDefaultWeight($params);
54 $params['value'] = $params['value'] ?? self
::getDefaultValue($params);
58 * Get next available value.
59 * We will take the highest numeric value (or 0 if no numeric values exist)
60 * and add one. The calling function is responsible for any
61 * more complex decision making
63 * @param array $params
67 public static function getDefaultWeight($params) {
68 return (int) CRM_Utils_Weight
::getDefaultWeight('CRM_Core_DAO_OptionValue',
69 ['option_group_id' => $params['option_group_id']]);
73 * Get next available value.
74 * We will take the highest numeric value (or 0 if no numeric values exist)
75 * and add one. The calling function is responsible for any
76 * more complex decision making
77 * @param array $params
79 public static function getDefaultValue($params) {
80 $bao = new CRM_Core_BAO_OptionValue();
81 $bao->option_group_id
= $params['option_group_id'];
82 if (isset($params['domain_id'])) {
83 $bao->domain_id
= $params['domain_id'];
86 $bao->whereAdd("value REGEXP '^[0-9]+$'");
87 $bao->selectAdd('(ROUND(COALESCE(MAX(CONVERT(value, UNSIGNED)),0)) +1) as nextvalue');
89 return $bao->nextvalue
;
93 * Fetch object based on array of properties.
95 * @param array $params
96 * (reference ) an assoc array of name/value pairs.
97 * @param array $defaults
98 * (reference ) an assoc array to hold the flattened values.
100 * @return CRM_Core_BAO_OptionValue
102 public static function retrieve(&$params, &$defaults) {
103 $optionValue = new CRM_Core_DAO_OptionValue();
104 $optionValue->copyValues($params);
105 if ($optionValue->find(TRUE)) {
106 CRM_Core_DAO
::storeValues($optionValue, $defaults);
113 * Update the is_active flag in the db.
116 * Id of the database record.
117 * @param bool $is_active
118 * Value we want to set the is_active field.
121 * true if we found and updated the object, else false
123 public static function setIsActive($id, $is_active) {
124 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_OptionValue', $id, 'is_active', $is_active);
128 * Add an Option Value.
130 * @param array $params
131 * Reference array contains the values submitted by the form.
133 * deprecated Reference array contains the id.
135 * @return \CRM_Core_DAO_OptionValue
137 * @throws \CRM_Core_Exception
138 * @throws \CiviCRM_API3_Exception
140 public static function add(&$params, $ids = []) {
141 if (!empty($ids['optionValue']) && empty($params['id'])) {
142 CRM_Core_Error
::deprecatedFunctionWarning('$params[\'id\'] should be set, $ids is deprecated');
144 $id = $params['id'] ??
$ids['optionValue'] ??
NULL;
146 // Update custom field data to reflect the new value
147 if ($id && isset($params['value'])) {
148 CRM_Core_BAO_CustomOption
::updateValue($id, $params['value']);
151 // We need to have option_group_id populated for validation so load if necessary.
152 if (empty($params['option_group_id'])) {
153 $params['option_group_id'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue',
154 $id, 'option_group_id', 'id'
157 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup',
158 $params['option_group_id'], 'name', 'id'
161 // action is taken depending upon the mode
162 $optionValue = new CRM_Core_DAO_OptionValue();
163 $optionValue->copyValues($params);
165 $isDomainOptionGroup = CRM_Core_OptionGroup
::isDomainOptionGroup($groupName);
166 // When creating a new option for a group that requires a domain, set default domain
167 if ($isDomainOptionGroup && empty($params['id']) && (empty($params['domain_id']) || CRM_Utils_System
::isNull($params['domain_id']))) {
168 $optionValue->domain_id
= CRM_Core_Config
::domainID();
171 // When setting a default option, unset other options in this group as default
172 // FIXME: The extra CRM_Utils_System::isNull is because the API will pass the string 'null'
173 // FIXME: It would help to make this column NOT NULL DEFAULT 0
174 if (!empty($params['is_default']) && !CRM_Utils_System
::isNull($params['is_default'])) {
175 $query = 'UPDATE civicrm_option_value SET is_default = 0 WHERE option_group_id = %1';
177 // tweak default reset, and allow multiple default within group.
178 if ($resetDefaultFor = CRM_Utils_Array
::value('reset_default_for', $params)) {
179 if (is_array($resetDefaultFor)) {
180 $colName = key($resetDefaultFor);
181 $colVal = $resetDefaultFor[$colName];
182 $query .= " AND ( $colName IN ( $colVal ) )";
186 $p = [1 => [$params['option_group_id'], 'Integer']];
188 // Limit update by domain of option
189 $domain = CRM_Utils_System
::isNull($optionValue->domain_id
) ?
NULL : $optionValue->domain_id
;
190 if (!$domain && $id && $isDomainOptionGroup) {
191 $domain = CRM_Core_DAO
::getFieldValue(__CLASS__
, $id, 'domain_id');
194 $query .= ' AND domain_id = %2';
195 $p[2] = [$domain, 'Integer'];
198 CRM_Core_DAO
::executeQuery($query, $p);
201 $groupsSupportingDuplicateValues = ['languages'];
202 if (!$id && !empty($params['value'])) {
203 $dao = new CRM_Core_DAO_OptionValue();
204 if (!in_array($groupName, $groupsSupportingDuplicateValues)) {
205 $dao->value
= $params['value'];
208 // CRM-21737 languages option group does not use unique values but unique names.
209 $dao->name
= $params['name'];
211 if (CRM_Core_OptionGroup
::isDomainOptionGroup($groupName)) {
212 $dao->domain_id
= $optionValue->domain_id
;
214 $dao->option_group_id
= $params['option_group_id'];
215 if ($dao->find(TRUE)) {
216 throw new CRM_Core_Exception('Value already exists in the database');
220 $optionValue->id
= $id;
221 $optionValue->save();
222 CRM_Core_PseudoConstant
::flush();
224 // Create relationship for payment instrument options
225 if (!empty($params['financial_account_id'])) {
226 $optionName = civicrm_api3('OptionGroup', 'getvalue', [
228 'id' => $params['option_group_id'],
230 // Only create relationship for payment instrument options
231 if ($optionName == 'payment_instrument') {
232 $relationTypeId = civicrm_api3('OptionValue', 'getvalue', [
234 'option_group_id' => 'account_relationship',
235 'name' => 'Asset Account is',
238 'entity_table' => 'civicrm_option_value',
239 'entity_id' => $optionValue->id
,
240 'account_relationship' => $relationTypeId,
241 'financial_account_id' => $params['financial_account_id'],
243 CRM_Financial_BAO_FinancialTypeAccount
::add($params);
250 * Delete Option Value.
252 * @param int $optionValueId
257 public static function del($optionValueId) {
258 $optionValue = new CRM_Core_DAO_OptionValue();
259 $optionValue->id
= $optionValueId;
260 if (!$optionValue->find()) {
263 $hookParams = ['id' => $optionValueId];
264 CRM_Utils_Hook
::pre('delete', 'OptionValue', $optionValueId, $hookParams);
265 if (self
::updateRecords($optionValueId, CRM_Core_Action
::DELETE
)) {
266 CRM_Core_PseudoConstant
::flush();
267 $optionValue->delete();
268 CRM_Utils_Hook
::post('delete', 'OptionValue', $optionValueId, $optionValue);
275 * Retrieve activity type label and description.
277 * @param int $activityTypeId
281 * label and description
283 public static function getActivityTypeDetails($activityTypeId) {
284 $query = "SELECT civicrm_option_value.label, civicrm_option_value.description
285 FROM civicrm_option_value
286 LEFT JOIN civicrm_option_group ON ( civicrm_option_value.option_group_id = civicrm_option_group.id )
287 WHERE civicrm_option_group.name = 'activity_type'
288 AND civicrm_option_value.value = {$activityTypeId} ";
290 $dao = CRM_Core_DAO
::executeQuery($query);
294 return [$dao->label
, $dao->description
];
298 * Get the Option Value title.
301 * Id of Option Value.
307 public static function getTitle($id) {
308 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $id, 'label');
312 * Updates contacts affected by the option value passed.
314 * @param int $optionValueId
315 * The option value id.
317 * The action describing whether prefix/suffix was UPDATED or DELETED.
321 public static function updateRecords(&$optionValueId, $action) {
323 $optionValue = new CRM_Core_DAO_OptionValue();
324 $optionValue->id
= $optionValueId;
325 $optionValue->find(TRUE);
327 $optionGroup = new CRM_Core_DAO_OptionGroup();
328 $optionGroup->id
= $optionValue->option_group_id
;
329 $optionGroup->find(TRUE);
332 $gName = $optionGroup->name
;
334 $value = $optionValue->value
;
336 // get the proper group name & affected field name
337 // todo: this may no longer be needed for individuals - check inputs
339 'gender' => 'gender_id',
340 'individual_prefix' => 'prefix_id',
341 'individual_suffix' => 'suffix_id',
342 'communication_style' => 'communication_style_id',
343 // Not only Individuals -- but the code seems to be generic for all contact types, despite the naming...
345 $contributions = ['payment_instrument' => 'payment_instrument_id'];
346 $activities = ['activity_type' => 'activity_type_id'];
347 $participant = ['participant_role' => 'role_id'];
348 $eventType = ['event_type' => 'event_type_id'];
349 $aclRole = ['acl_role' => 'acl_role_id'];
351 $all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole);
354 foreach ($all as $name => $id) {
355 if ($gName == $name) {
359 if ($fieldName == '') {
363 if (array_key_exists($gName, $individuals)) {
364 $contactDAO = new CRM_Contact_DAO_Contact();
366 $contactDAO->$fieldName = $value;
369 while ($contactDAO->fetch()) {
370 if ($action == CRM_Core_Action
::DELETE
) {
371 $contact = new CRM_Contact_DAO_Contact();
372 $contact->id
= $contactDAO->id
;
373 $contact->find(TRUE);
375 // make sure dates doesn't get reset
376 $contact->birth_date
= CRM_Utils_Date
::isoToMysql($contact->birth_date
);
377 $contact->deceased_date
= CRM_Utils_Date
::isoToMysql($contact->deceased_date
);
378 $contact->$fieldName = 'NULL';
386 if (array_key_exists($gName, $contributions)) {
387 $contribution = new CRM_Contribute_DAO_Contribution();
388 $contribution->$fieldName = $value;
389 $contribution->find();
390 while ($contribution->fetch()) {
391 if ($action == CRM_Core_Action
::DELETE
) {
392 $contribution->$fieldName = 'NULL';
393 $contribution->save();
399 if (array_key_exists($gName, $activities)) {
400 $activity = new CRM_Activity_DAO_Activity();
401 $activity->$fieldName = $value;
403 while ($activity->fetch()) {
409 //delete participant role, type and event type option value
410 if (array_key_exists($gName, $participant)) {
411 $participantValue = new CRM_Event_DAO_Participant();
412 $participantValue->$fieldName = $value;
413 if ($participantValue->find(TRUE)) {
419 //delete event type option value
420 if (array_key_exists($gName, $eventType)) {
421 $event = new CRM_Event_DAO_Event();
422 $event->$fieldName = $value;
423 if ($event->find(TRUE)) {
429 //delete acl_role option value
430 if (array_key_exists($gName, $aclRole)) {
431 $entityRole = new CRM_ACL_DAO_EntityRole();
432 $entityRole->$fieldName = $value;
434 $aclDAO = new CRM_ACL_DAO_ACL();
435 $aclDAO->entity_id
= $value;
436 if ($entityRole->find(TRUE) ||
$aclDAO->find(TRUE)) {
444 * Updates options values weights.
446 * @param int $opGroupId
447 * @param array $opWeights
448 * Options value , weight pair.
450 public static function updateOptionWeights($opGroupId, $opWeights) {
451 if (!is_array($opWeights) ||
empty($opWeights)) {
455 foreach ($opWeights as $opValue => $opWeight) {
456 $optionValue = new CRM_Core_DAO_OptionValue();
457 $optionValue->option_group_id
= $opGroupId;
458 $optionValue->value
= $opValue;
459 if ($optionValue->find(TRUE)) {
460 $optionValue->weight
= $opWeight;
461 $optionValue->save();
467 * Get the values of all option values given an option group ID. Store in system cache
468 * Does not take any filtering arguments. The object is to avoid hitting the DB and retrieve
471 * @param int $optionGroupID
472 * The option group for which we want the values from.
475 * an array of array of values for this option group
477 public static function getOptionValuesArray($optionGroupID) {
478 // check if we can get the field values from the system cache
479 $cacheKey = "CRM_Core_BAO_OptionValue_OptionGroupID_{$optionGroupID}";
480 $cache = CRM_Utils_Cache
::singleton();
481 $optionValues = $cache->get($cacheKey);
482 if (empty($optionValues)) {
483 $dao = new CRM_Core_DAO_OptionValue();
484 $dao->option_group_id
= $optionGroupID;
485 $dao->orderBy('weight ASC, label ASC');
489 while ($dao->fetch()) {
490 $optionValues[$dao->id
] = [];
491 CRM_Core_DAO
::storeValues($dao, $optionValues[$dao->id
]);
494 $cache->set($cacheKey, $optionValues);
497 return $optionValues;
501 * Get the values of all option values given an option group ID as a key => value pair
502 * Use above cached function to make it super efficient
504 * @param int $optionGroupID
505 * The option group for which we want the values from.
508 * an associative array of label, value pairs
510 public static function getOptionValuesAssocArray($optionGroupID) {
511 $optionValues = self
::getOptionValuesArray($optionGroupID);
514 foreach ($optionValues as $id => $value) {
515 $options[$value['value']] = $value['label'];
521 * Get the values of all option values given an option group Name as a key => value pair
522 * Use above cached function to make it super efficient
524 * @param string $optionGroupName
525 * The option group name for which we want the values from.
528 * an associative array of label, value pairs
530 public static function getOptionValuesAssocArrayFromName($optionGroupName) {
531 $dao = new CRM_Core_DAO_OptionGroup();
532 $dao->name
= $optionGroupName;
534 $dao->selectAdd('id');
536 $optionValues = self
::getOptionValuesArray($dao->id
);
539 foreach ($optionValues as $id => $value) {
540 $options[$value['value']] = $value['label'];
546 * Ensure an option value exists.
548 * This function is intended to be called from the upgrade script to ensure
549 * that an option value exists, without hitting an error if it already exists.
551 * This is sympathetic to sites who might pre-add it.
553 * @param array $params the option value attributes.
554 * @return array the option value attributes.
556 public static function ensureOptionValueExists($params) {
557 $result = civicrm_api3('OptionValue', 'get', [
558 'option_group_id' => $params['option_group_id'],
559 'name' => $params['name'],
560 'return' => ['id', 'value'],
564 if (!$result['count']) {
565 $result = civicrm_api3('OptionValue', 'create', $params);
568 return CRM_Utils_Array
::first($result['values']);