From 44f55016dc78432fb6cf19fa9a00d128287ea556 Mon Sep 17 00:00:00 2001 From: Coleman Watts Date: Tue, 16 Nov 2021 21:15:42 -0500 Subject: [PATCH] OptionValue - Fix incorrect update of `is_default` Checking `!empty($params['is_default'])` gave a false-positive for the string 'null'. --- CRM/Core/BAO/OptionValue.php | 4 +- .../phpunit/api/v4/Entity/OptionValueTest.php | 58 +++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 tests/phpunit/api/v4/Entity/OptionValueTest.php diff --git a/CRM/Core/BAO/OptionValue.php b/CRM/Core/BAO/OptionValue.php index 5414431659..cc40fb0e0d 100644 --- a/CRM/Core/BAO/OptionValue.php +++ b/CRM/Core/BAO/OptionValue.php @@ -175,7 +175,9 @@ class CRM_Core_BAO_OptionValue extends CRM_Core_DAO_OptionValue { } // When setting a default option, unset other options in this group as default - if (!empty($params['is_default'])) { + // FIXME: The extra CRM_Utils_System::isNull is because the API will pass the string 'null' + // FIXME: It would help to make this column NOT NULL DEFAULT 0 + if (!empty($params['is_default']) && !CRM_Utils_System::isNull($params['is_default'])) { $query = 'UPDATE civicrm_option_value SET is_default = 0 WHERE option_group_id = %1'; // tweak default reset, and allow multiple default within group. diff --git a/tests/phpunit/api/v4/Entity/OptionValueTest.php b/tests/phpunit/api/v4/Entity/OptionValueTest.php new file mode 100644 index 0000000000..470332c346 --- /dev/null +++ b/tests/phpunit/api/v4/Entity/OptionValueTest.php @@ -0,0 +1,58 @@ +addValue('name', 'myTestGroup') + ->addValue('title', 'myTestGroup') + ->execute(); + + $defaultId = OptionValue::create() + ->addValue('option_group_id.name', 'myTestGroup') + ->addValue('label', 'One') + ->addValue('value', 1) + ->addValue('is_default', TRUE) + ->execute()->first()['id']; + + $this->assertTrue(OptionValue::get(FALSE)->addWhere('id', '=', $defaultId)->execute()->first()['is_default']); + + // Now create a second option with is_default set to null. + // This should not interfere with the default setting in option one + OptionValue::create() + ->addValue('option_group_id.name', 'myTestGroup') + ->addValue('label', 'Two') + ->addValue('value', 2) + ->addValue('is_default', NULL) + ->execute(); + + $this->assertTrue(OptionValue::get(FALSE)->addWhere('id', '=', $defaultId)->execute()->first()['is_default']); + } + +} -- 2.25.1