APIv4 - Support FK field lookups in create/update/save actions
[civicrm-core.git] / Civi / Api4 / Generic / Traits / DAOActionTrait.php
index af611354480c2320c8082e248b86774715c7a329..76df9951a41d4b58eaaba7e34dd860be6bcaa49b 100644 (file)
@@ -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