Skip to content
Snippets Groups Projects
Commit 4fd13075 authored by colemanw's avatar colemanw
Browse files

APIv4 - Support FK field lookups in create/update/save actions

parent 182bc25d
Branches
Tags
No related merge requests found
......@@ -164,6 +164,35 @@ trait DAOActionTrait {
return $result;
}
/**
* @inheritDoc
*/
protected function formatWriteValues(&$record) {
$this->resolveFKValues($record);
parent::formatWriteValues($record);
}
/**
* Looks up an id based on some other property of an fk entity
*
* @param array $record
*/
private function resolveFKValues(array &$record): void {
foreach ($record as $key => $value) {
if (substr_count($key, '.') !== 1) {
continue;
}
[$fieldName, $fkField] = explode('.', $key);
$field = $this->entityFields()[$fieldName] ?? NULL;
if (!$field || empty($field['fk_entity'])) {
continue;
}
$fkDao = CoreUtil::getBAOFromApiName($field['fk_entity']);
$record[$fieldName] = \CRM_Core_DAO::getFieldValue($fkDao, $value, 'id', $fkField);
unset($record[$key]);
}
}
/**
* @param array $params
* @param int $entityId
......
......@@ -173,17 +173,18 @@ class FkJoinTest extends UnitTestCase {
->addValue('name', uniqid('join3'))
->execute()
->first()['name'];
// Create using pseudoconstant syntax (:name)
$cid1 = Contact::create(FALSE)
->addValue('first_name', 'Aaa')
->addChain('tag1', EntityTag::create()->setValues(['entity_id' => '$id', 'tag_id:name' => $tag1]))
->addChain('tag2', EntityTag::create()->setValues(['entity_id' => '$id', 'tag_id:name' => $tag2]))
->execute()
->first()['id'];
// Create using fk syntax (.name)
$cid2 = Contact::create(FALSE)
->addValue('first_name', 'Bbb')
->addChain('tag1', EntityTag::create()->setValues(['entity_id' => '$id', 'tag_id:name' => $tag1]))
->addChain('tag3', EntityTag::create()->setValues(['entity_id' => '$id', 'tag_id:name' => $tag3]))
->addChain('tag1', EntityTag::create()->setValues(['entity_id' => '$id', 'tag_id.name' => $tag1]))
->addChain('tag3', EntityTag::create()->setValues(['entity_id' => '$id', 'tag_id.name' => $tag3]))
->execute()
->first()['id'];
$cid3 = Contact::create(FALSE)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment