From 236737d5c7cff529f06948a6994d284b81f4d5b7 Mon Sep 17 00:00:00 2001 From: Coleman Watts Date: Thu, 20 Jan 2022 16:34:48 -0500 Subject: [PATCH] APIv4 - Use empty string instead of 'null' to pass null values to the database `CRM_Core_DAO::copyValues()` already converts '' to 'null', and passing the string 'null' into `BAO::writeRecords` or `BAO::create` functions prematurely can introduce subtle bugs because the string 'null' is `!empty()` whereas '' is `empty()`. --- Civi/Api4/Generic/Traits/DAOActionTrait.php | 4 ++-- Civi/Api4/Utils/FormattingUtil.php | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Civi/Api4/Generic/Traits/DAOActionTrait.php b/Civi/Api4/Generic/Traits/DAOActionTrait.php index 201f4c2ab9..b44c7d1fda 100644 --- a/Civi/Api4/Generic/Traits/DAOActionTrait.php +++ b/Civi/Api4/Generic/Traits/DAOActionTrait.php @@ -60,8 +60,8 @@ trait DAOActionTrait { else { $inputFields = array_keys($input); // Convert 'null' input to true null - foreach ($input as $key => $val) { - if ($val === 'null') { + foreach ($inputFields as $key) { + if (($bao->$key ?? NULL) === 'null') { $bao->$key = NULL; } } diff --git a/Civi/Api4/Utils/FormattingUtil.php b/Civi/Api4/Utils/FormattingUtil.php index f537e73b5e..6d4af31ed1 100644 --- a/Civi/Api4/Utils/FormattingUtil.php +++ b/Civi/Api4/Utils/FormattingUtil.php @@ -56,7 +56,8 @@ class FormattingUtil { /* * Because of the wacky way that database values are saved we need to format * some of the values here. In this strange world the string 'null' is used to - * unset values. Hence if we encounter true null we change it to string 'null'. + * unset values. If we encounter true null at this layer we change it to an empty string + * and it will be converted to 'null' by CRM_Core_DAO::copyValues. * * If we encounter the string 'null' then we assume the user actually wants to * set the value to string null. However since the string null is reserved for @@ -66,7 +67,7 @@ class FormattingUtil { * 'Null'. */ elseif (array_key_exists($name, $params) && $params[$name] === NULL) { - $params[$name] = 'null'; + $params[$name] = ''; } } -- 2.25.1