I've done this with the API. Pretty much everything you create in CiviCRM has a machine name field. This can be used as a known identifier, whereas the numerical Id fields cannot be known across different installations.
I made a helper which significantly shortened my install code:
/**
* Helper function for creating data structures.
*
* @param string $entity - name of the API entity.
* @param Array $params_min parameters to use for search.
* @param Array $params_extra these plus $params_min are used if a create call
* is needed.
*/
function pelf_get_or_create($entity, $params_min, $params_extra) {
$params_min += ['sequential' => 1];
$result = civicrm_api3($entity, 'get', $params_min);
if (!$result['count']) {
// Couldn't find it, create it now.
$result = civicrm_api3($entity, 'create', $params_extra + $params_min);
}
return $result['values'][0];
}
Then the install can do things like:
// Ensure we have the activity type set up for Prospects.
$my_activity_type = pelf_get_or_create('OptionValue', [
'option_group_id' => "activity_type",
'name' => "my_unique_activity",
],
[ 'label' => 'Something suitable']);
// Ensure we have the custom field group we need for prospects.
$customgroup = pelf_get_or_create('CustomGroup', [
'name' => "another_unique_name",
'extends' => "Activity",
'extends_entity_column_value' => $my_activity_type['value'],
],
['title' => 'Some custom Details']);
// Add a field.
$my_field_1 = pelf_get_or_create('CustomField', [
'name' => "another_name_for_field",
'custom_group_id' => $customgroup['id'],
'data_type' => "String",
'html_type' => "Text",
'is_required' => "1",
'default_value' => "0",
],
['label' => 'Explain it']);
Nb. I had to create a select field, too. This was a pain because you have to create the option group for its options, then all its options, then finally create the field itself, passing the id of the option group to the field create. I omitted it here because it's basically more of the same.
Anyway, with that code in my install hook, I can then easily fetch them in other code in my extension by using the names as lookups. AFAICS the name field is a machine-only field - there's usually a 'label' or 'title' field that is used by the UI.
activity_type_id
s created - by lookup by name/label or did you store the ID somewhere? I'm needing to do the same. Thanks.