Skip to content

APIv4 Chaining

Chaining lets you perform multiple API calls at once with the results of the outer call triggering additional api calls. E.g. to create a contact with a contribution you can nest the contribution create into the contact create. Likewise you can ask for all activities or all contributions to be returned from Contact::get.

Chaining or Joins

Chained API calls execute once per result. This can be very slow if the outer API call returns hundreds of records. In that case, consider if you can achieve your goal using Implicit or Explicit Joins instead.

Supported Syntaxes:

Object Oriented:

$results = \Civi\Api4\Contact::create()
  ->addValue('contact_type', 'Individual')
  ->addValue('display_name', 'BA Baracus')
  ->addChain('create_website', \Civi\Api4\Website::create()->setValues(['contact_id' => '$id', 'url' => 'example.com']))
  ->execute();

Traditional:

civicrm_api('Contact', 'create', [
  'version' => 4,
  'values' => [
    'contact_type' => 'Individual',
    'display_name' => 'BA Baracus',
  ],
  'chain' => [
    'create_website', ['Website', 'create', ['values' => ['url' => 'example.com', 'contact_id' => '$id']]],
  ],
]);

If you have 2 websites to create you can pass them as separate key => array pairs; just specify a unique array key in the chain array.

Object Oriented way

\Civi\Api4\Contact::create()
  ->addChain('first_website', \Civi\Api4\Website::create()->setValues(['contact_id' => '$id', 'url' => 'example1.com']))
  ->addChain('second_website', \Civi\Api4\Website::create()->setValues(['contact_id' => '$id', 'url' => 'example2.com']))
  ...

Traditional:

civicrm_api4('Contact', 'create', [
  'chain' => [
    'first website', ['Website', 'create', ['values' => ['url' => 'example1.com', 'contact_id' => '$id']]],
    'second_website', ['Website', 'create', ['values' => ['url' => 'example2.com', 'contact_id' => '$id']]],
  ],
  ...

Back-references

Note the use of '$id' in the examples above. Any field returned by the outer call can be passed down to a chained call by prefixing it with a dollar sign. Even the results of other chains can be accessed in this way.