Creating custom groups and custom fields programmatically in your drupal module

Publicat
2011-08-31 07:31
Written by
jamie - member of the CiviCRM community - view blog guidelines
I hope Michal will forgive me for typing during his Developer training presentation on tests. Since I heard the presentation at CiviCon, I instead tried, as an exercise based on what we learned this morning, to create a custom group and custom field via the install hook in a Drupal module. Here are the results...
 

function civicrmtest_install() {
  civicrm_initialize();
  require_once 'api/api.php';
  $params = array(
    'version' => 3,
    'extends' => array('Individual'),
    'title' => 'JamieGroup',
    'is_active' => 1,
  );
  $result = civicrm_api('CustomGroup','Create',$params);
  if($result['is_error'] == 1) {
    drupal_set_message('Error creating Custom Group');
    drupal_set_message($result['error_message']);
  } else {
    $value = array_pop($result['values']);
    $custom_group_id = $value['id'];
    variable_set('civicrmtest_custom_group_id',$custom_group_id);
    $params = array(
      'version' => 3,
      'label' => 'JamieField',
      'custom_group_id' => $custom_group_id,
      'is_active' => 1,
    );
    $result = civicrm_api('CustomField','Create',$params);
    if($result['is_error'] == 1) {
      drupal_set_message('Error creating Custom Field');
      drupal_set_message($result['error_message']);
    } else {
      $value = array_pop($result['values']);
      variable_set('civicrmtest_custom_field_id',$value['id']);
    }
  }
}

function civicrmtest_uninstall() {
  civicrm_initialize();
  require_once 'api/api.php';
  $custom_field_id = variable_get('civicrmtest_custom_field_id', null);
  if(!is_null($custom_field_id)) {
    $params = array(
      'version' => 3,
      'id' => $custom_field_id,
    );
    $result = civicrm_api('CustomField','Delete',$params);
    if($result['is_error'] == 1) {
      drupal_set_message('Error deleting Custom Field');
      drupal_set_message($result['error_message']);
    } else {
      variable_del('civicrmtest_custom_field_id');
    }
  }

  $custom_group_id = variable_get('civicrmtest_custom_group_id', null);
  if(!is_null($custom_group_id)) {
    $params = array(
      'version' => 3,
      'id' => $custom_group_id,
    );
    $result = civicrm_api('CustomGroup','Delete',$params);
    if($result['is_error'] == 1) {
      drupal_set_message('Error deleting Custom Group');
      drupal_set_message($result['error_message']);
    } else {
      variable_del('civicrmtest_custom_group_id');
    }
  }
}

Filed under

Comments

To continue the discussion we had about sensible default values during the sprint, is_active IMO should be an optional param that if not present defaults to true.