From 4c5b99371a8cc2d49ef8bc1749a11c87cb479f3b Mon Sep 17 00:00:00 2001 From: Coleman Watts Date: Thu, 27 Jan 2022 20:23:33 -0500 Subject: [PATCH] APIv4 - Correctly return date-only custom field values without the time --- Civi/Api4/Utils/FormattingUtil.php | 4 ++ .../api/v4/Action/BasicCustomFieldTest.php | 41 +++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/Civi/Api4/Utils/FormattingUtil.php b/Civi/Api4/Utils/FormattingUtil.php index f537e73b5e8b..5c20a9ef5bda 100644 --- a/Civi/Api4/Utils/FormattingUtil.php +++ b/Civi/Api4/Utils/FormattingUtil.php @@ -338,6 +338,10 @@ public static function convertDataType($value, $dataType) { case 'Money': case 'Float': return (float) $value; + + case 'Date': + // Strip time from date-only fields + return substr($value, 0, 10); } } return $value; diff --git a/tests/phpunit/api/v4/Action/BasicCustomFieldTest.php b/tests/phpunit/api/v4/Action/BasicCustomFieldTest.php index 4cc32bbcf010..d9728385a7d8 100644 --- a/tests/phpunit/api/v4/Action/BasicCustomFieldTest.php +++ b/tests/phpunit/api/v4/Action/BasicCustomFieldTest.php @@ -457,4 +457,45 @@ public function testUpdateWeights() { $this->assertEquals(['One' => 1, 'Two' => 2, 'Three' => 3, 'Four' => 4], $getValues('controlGroup')); } + /** + * Ensure custom date fields only return the date part + */ + public function testCustomDateFields(): void { + $cgName = uniqid('My'); + + CustomGroup::create(FALSE) + ->addValue('title', $cgName) + ->addValue('extends', 'Contact') + ->addChain('field1', CustomField::create() + ->addValue('label', 'DateOnly') + ->addValue('custom_group_id', '$id') + ->addValue('html_type', 'Select Date') + ->addValue('data_type', 'Date') + ->addValue('date_format', 'mm/dd/yy')) + ->addChain('field2', CustomField::create() + ->addValue('label', 'DateTime') + ->addValue('custom_group_id', '$id') + ->addValue('html_type', 'Select Date') + ->addValue('data_type', 'Date') + ->addValue('date_format', 'mm/dd/yy') + ->addValue('time_format', '1')) + ->execute(); + + $cid = Contact::create(FALSE) + ->addValue('first_name', 'Parent') + ->addValue('last_name', 'Tester') + ->addValue("$cgName.DateOnly", '2025-05-10') + ->addValue("$cgName.DateTime", '2025-06-11 12:15:30') + ->execute() + ->first()['id']; + $contact = Contact::get(FALSE) + ->addSelect('custom.*') + ->addWhere('id', '=', $cid) + ->execute()->first(); + // Date field should only return date part + $this->assertEquals('2025-05-10', $contact["$cgName.DateOnly"]); + // Date time field should return all + $this->assertEquals('2025-06-11 12:15:30', $contact["$cgName.DateTime"]); + } + }