Skip to content

Commit

Permalink
Merge pull request #22649 from colemanw/api4CustomDateFormat
Browse files Browse the repository at this point in the history
APIv4 - Correctly return date-only custom field values without the time
  • Loading branch information
colemanw authored Jan 28, 2022
2 parents fa0a6b7 + 4c5b993 commit 640b9d8
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Civi/Api4/Utils/FormattingUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
41 changes: 41 additions & 0 deletions tests/phpunit/api/v4/Action/BasicCustomFieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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"]);
}

}

0 comments on commit 640b9d8

Please sign in to comment.