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 * Retrieve DB object and copy to defaults array.
95 * @param array $params
96 * Array of criteria values.
97 * @param array $defaults
98 * Array to be populated with found values.
101 * The DAO object, if found.
105 public static function retrieve($params, &$defaults) {
106 return self
::commonRetrieve(self
::class, $params, $defaults);
110 * Update the is_active flag in the db.
113 * Id of the database record.
114 * @param bool $is_active
115 * Value we want to set the is_active field.
118 * true if we found and updated the object, else false
120 public static function setIsActive($id, $is_active) {
121 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_OptionValue', $id, 'is_active', $is_active);
125 * Add an Option Value.
127 * @param array $params
128 * Reference array contains the values submitted by the form.
130 * deprecated Reference array contains the id.
132 * @return \CRM_Core_DAO_OptionValue
134 * @throws \CRM_Core_Exception
135 * @throws \CiviCRM_API3_Exception
137 public static function add(&$params, $ids = []) {
138 if (!empty($ids['optionValue']) && empty($params['id'])) {
139 CRM_Core_Error
::deprecatedFunctionWarning('$params[\'id\'] should be set, $ids is deprecated');
141 $id = $params['id'] ??
$ids['optionValue'] ??
NULL;
143 // Update custom field data to reflect the new value
144 if ($id && isset($params['value'])) {
145 CRM_Core_BAO_CustomOption
::updateValue($id, $params['value']);
148 // We need to have option_group_id populated for validation so load if necessary.
149 if (empty($params['option_group_id'])) {
150 $params['option_group_id'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue',
151 $id, 'option_group_id', 'id'
154 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup',
155 $params['option_group_id'], 'name', 'id'
158 $op = $id ?
'edit' : 'create';
159 CRM_Utils_Hook
::pre($op, 'OptionValue', $id, $params);
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 CRM_Utils_Hook
::post($op, 'OptionValue', $id, $optionValue);
226 // Create relationship for payment instrument options
227 if (!empty($params['financial_account_id'])) {
228 $optionName = civicrm_api3('OptionGroup', 'getvalue', [
230 'id' => $params['option_group_id'],
232 // Only create relationship for payment instrument options
233 if ($optionName == 'payment_instrument') {
234 $relationTypeId = civicrm_api3('OptionValue', 'getvalue', [
236 'option_group_id' => 'account_relationship',
237 'name' => 'Asset Account is',
240 'entity_table' => 'civicrm_option_value',
241 'entity_id' => $optionValue->id
,
242 'account_relationship' => $relationTypeId,
243 'financial_account_id' => $params['financial_account_id'],
245 CRM_Financial_BAO_FinancialTypeAccount
::add($params);
252 * Delete Option Value.
254 * @param int $optionValueId
259 public static function del($optionValueId) {
260 $optionValue = new CRM_Core_DAO_OptionValue();
261 $optionValue->id
= $optionValueId;
262 if (!$optionValue->find()) {
265 $hookParams = ['id' => $optionValueId];
266 CRM_Utils_Hook
::pre('delete', 'OptionValue', $optionValueId, $hookParams);
267 if (self
::updateRecords($optionValueId, CRM_Core_Action
::DELETE
)) {
268 CRM_Core_PseudoConstant
::flush();
269 $optionValue->delete();
270 CRM_Utils_Hook
::post('delete', 'OptionValue', $optionValueId, $optionValue);
277 * Retrieve activity type label and description.
279 * @param int $activityTypeId
283 * label and description
285 public static function getActivityTypeDetails($activityTypeId) {
286 $query = "SELECT civicrm_option_value.label, civicrm_option_value.description
287 FROM civicrm_option_value
288 LEFT JOIN civicrm_option_group ON ( civicrm_option_value.option_group_id = civicrm_option_group.id )
289 WHERE civicrm_option_group.name = 'activity_type'
290 AND civicrm_option_value.value = {$activityTypeId} ";
292 $dao = CRM_Core_DAO
::executeQuery($query);
296 return [$dao->label
, $dao->description
];
300 * Get the Option Value title.
303 * Id of Option Value.
309 public static function getTitle($id) {
310 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $id, 'label');
314 * Updates contacts affected by the option value passed.
316 * @param int $optionValueId
317 * The option value id.
319 * The action describing whether prefix/suffix was UPDATED or DELETED.
323 public static function updateRecords(&$optionValueId, $action) {
325 $optionValue = new CRM_Core_DAO_OptionValue();
326 $optionValue->id
= $optionValueId;
327 $optionValue->find(TRUE);
329 $optionGroup = new CRM_Core_DAO_OptionGroup();
330 $optionGroup->id
= $optionValue->option_group_id
;
331 $optionGroup->find(TRUE);
334 $gName = $optionGroup->name
;
336 $value = $optionValue->value
;
338 // get the proper group name & affected field name
339 // todo: this may no longer be needed for individuals - check inputs
341 'gender' => 'gender_id',
342 'individual_prefix' => 'prefix_id',
343 'individual_suffix' => 'suffix_id',
344 'communication_style' => 'communication_style_id',
345 // Not only Individuals -- but the code seems to be generic for all contact types, despite the naming...
347 $contributions = ['payment_instrument' => 'payment_instrument_id'];
348 $activities = ['activity_type' => 'activity_type_id'];
349 $participant = ['participant_role' => 'role_id'];
350 $eventType = ['event_type' => 'event_type_id'];
351 $aclRole = ['acl_role' => 'acl_role_id'];
353 $all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole);
356 foreach ($all as $name => $id) {
357 if ($gName == $name) {
361 if ($fieldName == '') {
365 if (array_key_exists($gName, $individuals)) {
366 $contactDAO = new CRM_Contact_DAO_Contact();
368 $contactDAO->$fieldName = $value;
371 while ($contactDAO->fetch()) {
372 if ($action == CRM_Core_Action
::DELETE
) {
373 $contact = new CRM_Contact_DAO_Contact();
374 $contact->id
= $contactDAO->id
;
375 $contact->find(TRUE);
377 // make sure dates doesn't get reset
378 $contact->birth_date
= CRM_Utils_Date
::isoToMysql($contact->birth_date
);
379 $contact->deceased_date
= CRM_Utils_Date
::isoToMysql($contact->deceased_date
);
380 $contact->$fieldName = 'NULL';
388 if (array_key_exists($gName, $contributions)) {
389 $contribution = new CRM_Contribute_DAO_Contribution();
390 $contribution->$fieldName = $value;
391 $contribution->find();
392 while ($contribution->fetch()) {
393 if ($action == CRM_Core_Action
::DELETE
) {
394 $contribution->$fieldName = 'NULL';
395 $contribution->save();
401 if (array_key_exists($gName, $activities)) {
402 $activity = new CRM_Activity_DAO_Activity();
403 $activity->$fieldName = $value;
405 while ($activity->fetch()) {
411 //delete participant role, type and event type option value
412 if (array_key_exists($gName, $participant)) {
413 $participantValue = new CRM_Event_DAO_Participant();
414 $participantValue->$fieldName = $value;
415 if ($participantValue->find(TRUE)) {
421 //delete event type option value
422 if (array_key_exists($gName, $eventType)) {
423 $event = new CRM_Event_DAO_Event();
424 $event->$fieldName = $value;
425 if ($event->find(TRUE)) {
431 //delete acl_role option value
432 if (array_key_exists($gName, $aclRole)) {
433 $entityRole = new CRM_ACL_DAO_EntityRole();
434 $entityRole->$fieldName = $value;
436 $aclDAO = new CRM_ACL_DAO_ACL();
437 $aclDAO->entity_id
= $value;
438 if ($entityRole->find(TRUE) ||
$aclDAO->find(TRUE)) {
446 * Updates options values weights.
448 * @param int $opGroupId
449 * @param array $opWeights
450 * Options value , weight pair.
452 public static function updateOptionWeights($opGroupId, $opWeights) {
453 if (!is_array($opWeights) ||
empty($opWeights)) {
457 foreach ($opWeights as $opValue => $opWeight) {
458 $optionValue = new CRM_Core_DAO_OptionValue();
459 $optionValue->option_group_id
= $opGroupId;
460 $optionValue->value
= $opValue;
461 if ($optionValue->find(TRUE)) {
462 $optionValue->weight
= $opWeight;
463 $optionValue->save();
469 * Get the values of all option values given an option group ID. Store in system cache
470 * Does not take any filtering arguments. The object is to avoid hitting the DB and retrieve
473 * @param int $optionGroupID
474 * The option group for which we want the values from.
477 * an array of array of values for this option group
479 public static function getOptionValuesArray($optionGroupID) {
480 // check if we can get the field values from the system cache
481 $cacheKey = "CRM_Core_BAO_OptionValue_OptionGroupID_{$optionGroupID}";
482 $cache = CRM_Utils_Cache
::singleton();
483 $optionValues = $cache->get($cacheKey);
484 if (empty($optionValues)) {
485 $dao = new CRM_Core_DAO_OptionValue();
486 $dao->option_group_id
= $optionGroupID;
487 $dao->orderBy('weight ASC, label ASC');
491 while ($dao->fetch()) {
492 $optionValues[$dao->id
] = [];
493 CRM_Core_DAO
::storeValues($dao, $optionValues[$dao->id
]);
496 $cache->set($cacheKey, $optionValues);
499 return $optionValues;
503 * Get the values of all option values given an option group ID as a key => value pair
504 * Use above cached function to make it super efficient
506 * @param int $optionGroupID
507 * The option group for which we want the values from.
510 * an associative array of label, value pairs
512 public static function getOptionValuesAssocArray($optionGroupID) {
513 $optionValues = self
::getOptionValuesArray($optionGroupID);
516 foreach ($optionValues as $id => $value) {
517 $options[$value['value']] = $value['label'];
523 * Get the values of all option values given an option group Name as a key => value pair
524 * Use above cached function to make it super efficient
526 * @param string $optionGroupName
527 * The option group name for which we want the values from.
530 * an associative array of label, value pairs
532 public static function getOptionValuesAssocArrayFromName($optionGroupName) {
533 $dao = new CRM_Core_DAO_OptionGroup();
534 $dao->name
= $optionGroupName;
536 $dao->selectAdd('id');
538 $optionValues = self
::getOptionValuesArray($dao->id
);
541 foreach ($optionValues as $id => $value) {
542 $options[$value['value']] = $value['label'];
548 * Ensure an option value exists.
550 * This function is intended to be called from the upgrade script to ensure
551 * that an option value exists, without hitting an error if it already exists.
553 * This is sympathetic to sites who might pre-add it.
555 * @param array $params the option value attributes.
556 * @return array the option value attributes.
558 public static function ensureOptionValueExists($params) {
559 $result = civicrm_api3('OptionValue', 'get', [
560 'option_group_id' => $params['option_group_id'],
561 'name' => $params['name'],
562 'return' => ['id', 'value'],
566 if (!$result['count']) {
567 $result = civicrm_api3('OptionValue', 'create', $params);
570 return CRM_Utils_Array
::first($result['values']);