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
{
22 public function __construct() {
23 parent
::__construct();
27 * Create option value.
29 * Note that the create function calls 'add' but has more business logic.
31 * @param array $params
36 public static function create($params) {
37 if (empty($params['id'])) {
38 self
::setDefaults($params);
41 if (!empty($params['id'])) {
42 $ids = ['optionValue' => $params['id']];
44 return CRM_Core_BAO_OptionValue
::add($params, $ids);
48 * Set default Parameters.
49 * This functions sets default parameters if not set:
50 * - name & label are set to each other as required (it might make more sense for one
51 * to be required but this would mean a change to the api level)
52 * - weight & value will be set to their respective option groups next values
53 * if nothing is passed in.
55 * Note this function does not check for presence of $params['id'] so should only be called
56 * if 'id' is not present
58 * @param array $params
60 public static function setDefaults(&$params) {
61 if (CRM_Utils_Array
::value('label', $params, NULL) === NULL) {
62 $params['label'] = $params['name'];
64 if (CRM_Utils_Array
::value('name', $params, NULL) === NULL) {
65 $params['name'] = $params['label'];
67 if (CRM_Utils_Array
::value('weight', $params, NULL) === NULL) {
68 $params['weight'] = self
::getDefaultWeight($params);
70 if (CRM_Utils_Array
::value('value', $params, NULL) === NULL) {
71 $params['value'] = self
::getDefaultValue($params);
76 * Get next available value.
77 * We will take the highest numeric value (or 0 if no numeric values exist)
78 * and add one. The calling function is responsible for any
79 * more complex decision making
81 * @param array $params
85 public static function getDefaultWeight($params) {
86 return (int) CRM_Utils_Weight
::getDefaultWeight('CRM_Core_DAO_OptionValue',
87 ['option_group_id' => $params['option_group_id']]);
91 * Get next available value.
92 * We will take the highest numeric value (or 0 if no numeric values exist)
93 * and add one. The calling function is responsible for any
94 * more complex decision making
95 * @param array $params
97 public static function getDefaultValue($params) {
98 $bao = new CRM_Core_BAO_OptionValue();
99 $bao->option_group_id
= $params['option_group_id'];
100 if (isset($params['domain_id'])) {
101 $bao->domain_id
= $params['domain_id'];
104 $bao->whereAdd("value REGEXP '^[0-9]+$'");
105 $bao->selectAdd('(ROUND(COALESCE(MAX(CONVERT(value, UNSIGNED)),0)) +1) as nextvalue');
107 return $bao->nextvalue
;
111 * Fetch object based on array of properties.
113 * @param array $params
114 * (reference ) an assoc array of name/value pairs.
115 * @param array $defaults
116 * (reference ) an assoc array to hold the flattened values.
118 * @return CRM_Core_BAO_OptionValue
120 public static function retrieve(&$params, &$defaults) {
121 $optionValue = new CRM_Core_DAO_OptionValue();
122 $optionValue->copyValues($params);
123 if ($optionValue->find(TRUE)) {
124 CRM_Core_DAO
::storeValues($optionValue, $defaults);
131 * Update the is_active flag in the db.
134 * Id of the database record.
135 * @param bool $is_active
136 * Value we want to set the is_active field.
139 * true if we found and updated the object, else false
141 public static function setIsActive($id, $is_active) {
142 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_OptionValue', $id, 'is_active', $is_active);
146 * Add an Option Value.
148 * @param array $params
149 * Reference array contains the values submitted by the form.
151 * deprecated Reference array contains the id.
153 * @return \CRM_Core_DAO_OptionValue
154 * @throws \CRM_Core_Exception
156 public static function add(&$params, $ids = []) {
157 $id = $params['id'] ??
$ids['optionValue'] ??
NULL;
158 // CRM-10921: do not reset attributes to default if this is an update
159 //@todo consider if defaults are being set in the right place. 'dumb' defaults like
160 // these would be usefully set @ the api layer so they are visible to api users
161 // complex defaults like the domain id below would make sense in the setDefauls function
162 // but unclear what other ways this function is being used
164 $params['is_active'] = CRM_Utils_Array
::value('is_active', $params, FALSE);
165 $params['is_default'] = CRM_Utils_Array
::value('is_default', $params, FALSE);
166 $params['is_optgroup'] = CRM_Utils_Array
::value('is_optgroup', $params, FALSE);
167 $params['filter'] = CRM_Utils_Array
::value('filter', $params, FALSE);
169 // Update custom field data to reflect the new value
170 elseif (isset($params['value'])) {
171 CRM_Core_BAO_CustomOption
::updateValue($id, $params['value']);
174 // We need to have option_group_id populated for validation so load if necessary.
175 if (empty($params['option_group_id'])) {
176 $params['option_group_id'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue',
177 $id, 'option_group_id', 'id'
180 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup',
181 $params['option_group_id'], 'name', 'id'
184 // action is taken depending upon the mode
185 $optionValue = new CRM_Core_DAO_OptionValue();
186 $optionValue->copyValues($params);
188 if (!empty($params['is_default'])) {
189 $query = 'UPDATE civicrm_option_value SET is_default = 0 WHERE option_group_id = %1';
191 // tweak default reset, and allow multiple default within group.
192 if ($resetDefaultFor = CRM_Utils_Array
::value('reset_default_for', $params)) {
193 if (is_array($resetDefaultFor)) {
194 $colName = key($resetDefaultFor);
195 $colVal = $resetDefaultFor[$colName];
196 $query .= " AND ( $colName IN ( $colVal ) )";
200 $p = [1 => [$params['option_group_id'], 'Integer']];
201 CRM_Core_DAO
::executeQuery($query, $p);
204 if (empty($params['domain_id']) && in_array($groupName, CRM_Core_OptionGroup
::$_domainIDGroups)) {
205 $optionValue->domain_id
= CRM_Core_Config
::domainID();
208 $groupsSupportingDuplicateValues = ['languages'];
209 if (!$id && !empty($params['value'])) {
210 $dao = new CRM_Core_DAO_OptionValue();
211 if (!in_array($groupName, $groupsSupportingDuplicateValues)) {
212 $dao->value
= $params['value'];
215 // CRM-21737 languages option group does not use unique values but unique names.
216 $dao->name
= $params['name'];
218 if (in_array($groupName, CRM_Core_OptionGroup
::$_domainIDGroups)) {
219 $dao->domain_id
= $optionValue->domain_id
;
221 $dao->option_group_id
= $params['option_group_id'];
222 if ($dao->find(TRUE)) {
223 throw new CRM_Core_Exception('Value already exists in the database');
227 $optionValue->id
= $id;
228 $optionValue->save();
229 CRM_Core_PseudoConstant
::flush();
231 // Create relationship for payment instrument options
232 if (!empty($params['financial_account_id'])) {
233 $optionName = civicrm_api3('OptionGroup', 'getvalue', [
235 'id' => $params['option_group_id'],
237 // Only create relationship for payment instrument options
238 if ($optionName == 'payment_instrument') {
239 $relationTypeId = civicrm_api3('OptionValue', 'getvalue', [
241 'option_group_id' => 'account_relationship',
242 'name' => 'Asset Account is',
245 'entity_table' => 'civicrm_option_value',
246 'entity_id' => $optionValue->id
,
247 'account_relationship' => $relationTypeId,
248 'financial_account_id' => $params['financial_account_id'],
250 CRM_Financial_BAO_FinancialTypeAccount
::add($params);
257 * Delete Option Value.
259 * @param int $optionValueId
264 public static function del($optionValueId) {
265 $optionValue = new CRM_Core_DAO_OptionValue();
266 $optionValue->id
= $optionValueId;
267 if (!$optionValue->find()) {
270 if (self
::updateRecords($optionValueId, CRM_Core_Action
::DELETE
)) {
271 CRM_Core_PseudoConstant
::flush();
272 $optionValue->delete();
279 * Retrieve activity type label and description.
281 * @param int $activityTypeId
285 * label and description
287 public static function getActivityTypeDetails($activityTypeId) {
288 $query = "SELECT civicrm_option_value.label, civicrm_option_value.description
289 FROM civicrm_option_value
290 LEFT JOIN civicrm_option_group ON ( civicrm_option_value.option_group_id = civicrm_option_group.id )
291 WHERE civicrm_option_group.name = 'activity_type'
292 AND civicrm_option_value.value = {$activityTypeId} ";
294 $dao = CRM_Core_DAO
::executeQuery($query);
298 return [$dao->label
, $dao->description
];
302 * Get the Option Value title.
305 * Id of Option Value.
311 public static function getTitle($id) {
312 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $id, 'label');
316 * Updates contacts affected by the option value passed.
318 * @param int $optionValueId
319 * The option value id.
321 * The action describing whether prefix/suffix was UPDATED or DELETED.
325 public static function updateRecords(&$optionValueId, $action) {
327 $optionValue = new CRM_Core_DAO_OptionValue();
328 $optionValue->id
= $optionValueId;
329 $optionValue->find(TRUE);
331 $optionGroup = new CRM_Core_DAO_OptionGroup();
332 $optionGroup->id
= $optionValue->option_group_id
;
333 $optionGroup->find(TRUE);
336 $gName = $optionGroup->name
;
338 $value = $optionValue->value
;
340 // get the proper group name & affected field name
341 // todo: this may no longer be needed for individuals - check inputs
343 'gender' => 'gender_id',
344 'individual_prefix' => 'prefix_id',
345 'individual_suffix' => 'suffix_id',
346 'communication_style' => 'communication_style_id',
347 // Not only Individuals -- but the code seems to be generic for all contact types, despite the naming...
349 $contributions = ['payment_instrument' => 'payment_instrument_id'];
350 $activities = ['activity_type' => 'activity_type_id'];
351 $participant = ['participant_role' => 'role_id'];
352 $eventType = ['event_type' => 'event_type_id'];
353 $aclRole = ['acl_role' => 'acl_role_id'];
355 $all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole);
358 foreach ($all as $name => $id) {
359 if ($gName == $name) {
363 if ($fieldName == '') {
367 if (array_key_exists($gName, $individuals)) {
368 $contactDAO = new CRM_Contact_DAO_Contact();
370 $contactDAO->$fieldName = $value;
373 while ($contactDAO->fetch()) {
374 if ($action == CRM_Core_Action
::DELETE
) {
375 $contact = new CRM_Contact_DAO_Contact();
376 $contact->id
= $contactDAO->id
;
377 $contact->find(TRUE);
379 // make sure dates doesn't get reset
380 $contact->birth_date
= CRM_Utils_Date
::isoToMysql($contact->birth_date
);
381 $contact->deceased_date
= CRM_Utils_Date
::isoToMysql($contact->deceased_date
);
382 $contact->$fieldName = 'NULL';
390 if (array_key_exists($gName, $contributions)) {
391 $contribution = new CRM_Contribute_DAO_Contribution();
392 $contribution->$fieldName = $value;
393 $contribution->find();
394 while ($contribution->fetch()) {
395 if ($action == CRM_Core_Action
::DELETE
) {
396 $contribution->$fieldName = 'NULL';
397 $contribution->save();
403 if (array_key_exists($gName, $activities)) {
404 $activity = new CRM_Activity_DAO_Activity();
405 $activity->$fieldName = $value;
407 while ($activity->fetch()) {
413 //delete participant role, type and event type option value
414 if (array_key_exists($gName, $participant)) {
415 $participantValue = new CRM_Event_DAO_Participant();
416 $participantValue->$fieldName = $value;
417 if ($participantValue->find(TRUE)) {
423 //delete event type option value
424 if (array_key_exists($gName, $eventType)) {
425 $event = new CRM_Event_DAO_Event();
426 $event->$fieldName = $value;
427 if ($event->find(TRUE)) {
433 //delete acl_role option value
434 if (array_key_exists($gName, $aclRole)) {
435 $entityRole = new CRM_ACL_DAO_EntityRole();
436 $entityRole->$fieldName = $value;
438 $aclDAO = new CRM_ACL_DAO_ACL();
439 $aclDAO->entity_id
= $value;
440 if ($entityRole->find(TRUE) ||
$aclDAO->find(TRUE)) {
448 * Updates options values weights.
450 * @param int $opGroupId
451 * @param array $opWeights
452 * Options value , weight pair.
454 public static function updateOptionWeights($opGroupId, $opWeights) {
455 if (!is_array($opWeights) ||
empty($opWeights)) {
459 foreach ($opWeights as $opValue => $opWeight) {
460 $optionValue = new CRM_Core_DAO_OptionValue();
461 $optionValue->option_group_id
= $opGroupId;
462 $optionValue->value
= $opValue;
463 if ($optionValue->find(TRUE)) {
464 $optionValue->weight
= $opWeight;
465 $optionValue->save();
471 * Get the values of all option values given an option group ID. Store in system cache
472 * Does not take any filtering arguments. The object is to avoid hitting the DB and retrieve
475 * @param int $optionGroupID
476 * The option group for which we want the values from.
479 * an array of array of values for this option group
481 public static function getOptionValuesArray($optionGroupID) {
482 // check if we can get the field values from the system cache
483 $cacheKey = "CRM_Core_BAO_OptionValue_OptionGroupID_{$optionGroupID}";
484 $cache = CRM_Utils_Cache
::singleton();
485 $optionValues = $cache->get($cacheKey);
486 if (empty($optionValues)) {
487 $dao = new CRM_Core_DAO_OptionValue();
488 $dao->option_group_id
= $optionGroupID;
489 $dao->orderBy('weight ASC, label ASC');
493 while ($dao->fetch()) {
494 $optionValues[$dao->id
] = [];
495 CRM_Core_DAO
::storeValues($dao, $optionValues[$dao->id
]);
498 $cache->set($cacheKey, $optionValues);
501 return $optionValues;
505 * Get the values of all option values given an option group ID as a key => value pair
506 * Use above cached function to make it super efficient
508 * @param int $optionGroupID
509 * The option group for which we want the values from.
512 * an associative array of label, value pairs
514 public static function getOptionValuesAssocArray($optionGroupID) {
515 $optionValues = self
::getOptionValuesArray($optionGroupID);
518 foreach ($optionValues as $id => $value) {
519 $options[$value['value']] = $value['label'];
525 * Get the values of all option values given an option group Name as a key => value pair
526 * Use above cached function to make it super efficient
528 * @param string $optionGroupName
529 * The option group name for which we want the values from.
532 * an associative array of label, value pairs
534 public static function getOptionValuesAssocArrayFromName($optionGroupName) {
535 $dao = new CRM_Core_DAO_OptionGroup();
536 $dao->name
= $optionGroupName;
538 $dao->selectAdd('id');
540 $optionValues = self
::getOptionValuesArray($dao->id
);
543 foreach ($optionValues as $id => $value) {
544 $options[$value['value']] = $value['label'];
550 * Ensure an option value exists.
552 * This function is intended to be called from the upgrade script to ensure
553 * that an option value exists, without hitting an error if it already exists.
555 * This is sympathetic to sites who might pre-add it.
557 * @param array $params the option value attributes.
558 * @return array the option value attributes.
560 public static function ensureOptionValueExists($params) {
561 $result = civicrm_api3('OptionValue', 'get', [
562 'option_group_id' => $params['option_group_id'],
563 'name' => $params['name'],
564 'return' => ['id', 'value'],
568 if (!$result['count']) {
569 $result = civicrm_api3('OptionValue', 'create', $params);
572 return CRM_Utils_Array
::first($result['values']);