Skip to content

Instantly share code, notes, and snippets.

@michaelmcandrew
Created March 19, 2018 22:35
Show Gist options
  • Save michaelmcandrew/21754058092bfd63504490f59ae19944 to your computer and use it in GitHub Desktop.
Save michaelmcandrew/21754058092bfd63504490f59ae19944 to your computer and use it in GitHub Desktop.
Creating related entities in CiviCRM
<?php
// Reference other entities in params with '{{entity.tag}}'
echo "Creating demo data...\n";
$entities['ChatConversationType'] = [
'pets' => [
'name' => 'Cats or dogs?',
'timeout' => '30'
],
'fullName' => [
'name' => 'Your name',
'timeout' => '30'
],
];
$entities['ChatHear'] = [
'petsurvey' => [
'text' => 'pet survey',
'chat_conversation_type_id' => '{{ChatConversationType.pets}}'
]
];
$entities['ChatQuestion'] = [
'dogorcat' => [
'conversation_type_id' => '{{ChatConversationType.pets}}',
'text' => 'Are you a dog person or a cat person?',
],
'dog' => [
'conversation_type_id' => '{{ChatConversationType.pets}}',
'text' => 'Do you have a dog?',
],
'cat' => [
'conversation_type_id' => '{{ChatConversationType.pets}}',
'text' => 'Do you have a cat?',
],
'catsName' => [
'conversation_type_id' => '{{ChatConversationType.pets}}',
'text' => 'What is your cats name?',
],
'dogNewsletter' => [
'conversation_type_id' => '{{ChatConversationType.pets}}',
'text' => 'Would you like to join our newsletter for Dog owners?'
],
'firstName' => [
'conversation_type_id' => '{{ChatConversationType.fullName}}',
'text' => 'What is your first name?',
],
'lastName' => [
'conversation_type_id' => '{{ChatConversationType.fullName}}',
'text' => 'What is your last name?',
],
];
$created = [];
while(createEntities($entities, $created));
function createEntities(&$entities, &$created){
foreach($entities as $type => $objects){
foreach($objects as $tag => $params){
if(substitute($params, $created)){
$result = civicrm_api3($type, 'create', $params);
$created[$type][$tag] = $result['id'];
unset($entities[$type][$tag]);
}
}
if(count($entities[$type] == 0)){
unset($entities[$type]);
}
}
return count($entities);
}
function substitute(&$params, $created){
foreach($params as $key => $value){
if(preg_match("/^{{(.*)\.(.*)}}$/", $value, $matches)){
if(isset($created[$matches[1]][$matches[2]])){
$params[$key] = $created[$matches[1]][$matches[2]];
}else{
return false;
}
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment