CiviCRM Community Forums (archive)

*

News:

Have a question about CiviCRM?
Get it answered quickly at the new
CiviCRM Stack Exchange Q+A site

This forum was archived on 25 November 2017. Learn more.
How to get involved.
What to do if you think you've found a bug.



  • CiviCRM Community Forums (archive) »
  • Old sections (read-only, deprecated) »
  • Developer Discussion (Moderator: Donald Lobo) »
  • Sample code to create custom groups and fields
Pages: [1]

Author Topic: Sample code to create custom groups and fields  (Read 2153 times)

druderman

  • I’m new here
  • *
  • Posts: 24
  • Karma: 0
  • CiviCRM version: 4.1+
  • CMS version: Drupal 7
  • MySQL version: 5.0.77 and 5.1
  • PHP version: 5.2.13
Sample code to create custom groups and fields
April 18, 2012, 12:33:25 pm
I need to create fields on a development server and then recreate them in production.

With CiviCRM, it felt like you should be able to export the field definitions and then import them, but I couldn't track that down.
There is plenty of sample code that ships with CiviCRM, but I couldn't find sample V3 API code to do all of what I wanted, so I decided to write my own.  I'm using CiviCRM 4.1.

Here's some V3 API code to create the custom groups and fields. This solution is not at all generalized, but is quite helpful for what I'm doing.

First set up an array of Groups, Fields, and optional Values.
Below Academic is a group. Programs and Subjects are text fields. The rest are Select fields with options.

Code: [Select]
 
$configuration = array (
    'Academic' => array(
        'Programs' => array(
            'html_type' => 'text'
        ),
        'Subjects' => array(
            'html_type' => 'text'
        ),
        'Educational Level Completed' => array(
            'html_type' => 'Select',
            'option_values' => array(
                array('label' => 'H.S. Degree',
                    'value' => 'ed_level_hs_degree',
                    'is_active'=> TRUE,
                    'weight' => 1
                ),
                array('label' => 'Some College',
                    'value' => 'ed_level_some_college',
                    'is_active'=> TRUE,
                    'weight' => 1
                ),
                array('label' => "Associate's Degree",
                    'value' => 'ed_level_associates',
                    'is_active'=> TRUE,
                    'weight' => 1
                ),
                array('label' => "Bachelor's Degree",
                    'value' => 'ed_level_bachelors',
                    'is_active'=> TRUE,
                    'weight' => 1
                ),
            ),
        ),
        'Educational Goal' => array(
            'html_type' => 'Select',
            'option_values' => array(
                array('label' => 'Doctorate',
                    'value' => 'ed_goal_doctorate',
                    'is_active'=> TRUE,
                    'weight' => 1
                ),
                array('label' => "Master's Degree",
                    'value' => 'ed_goal_masters',
                    'is_active'=> TRUE,
                    'weight' => 1
                ),
                array('label' => "Bachelor's Degree",
                    'value' => 'ed_goal_bachelors',
                    'is_active'=> TRUE,
                    'weight' => 1
                ),
                array('label' => "Associate's Degree",
                    'value' => 'ed_goal_associates',
                    'is_active'=> TRUE,
                    'weight' => 1
                ),
            ),
        ),
        'Educational Timeframe' => array(
            'html_type' => 'Select',
            'option_values' => array(
                array('label' => '1-3 months',
                    'value' => 'ed_timeframe_1_3_months',
                    'is_active'=> TRUE,
                    'weight' => 1
                ),
                array('label' => "3-6 months",
                    'value' => 'ed_timeframe_3_6_months',
                    'is_active'=> TRUE,
                    'weight' => 1
                ),
                array('label' => "6-12 months",
                    'value' => 'ed_timeframe_6_12_months',
                    'is_active'=> TRUE,
                    'weight' => 1
                ),
                array('label' => "12-24 months",
                    'value' => 'ed_timeframe_12_24_months',
                    'is_active'=> TRUE,
                    'weight' => 1
                ),
            ),
        ),
    ),
  ); 


Then loop through the Groups and Fields and create them if they do not exist.
Code: [Select]
 
  // Create groups
  foreach($configuration as $title => $group_vals) {
    $group_id = 0;
    $result = get_custom_field_group_info($title);
   
    if ($result['count'] > 0) {
      $group_id = $result['id'];
    } else {
      $result = create_custom_field_group($title);
      $group_id = $result['id'];
    }

    // Create fields   
    foreach ($group_vals as $title => $field_vals) {
      $result = get_custom_field_info($title);
      if ($result['count'] == 0) {     
        create_custom_field($title, $group_id, $field_vals);
      }
    }   
  }   

These are short utility functions to create and get groups and fields.

Code: [Select]
function get_custom_field_info($name) {
 
  $params = array(
      'version' => 3,
      'name' =>  str_replace(' ', '_', $name),
  );
  $result = civicrm_api('custom_field', 'get', $params);
 
  return $result;
}

function create_custom_field($title, $group_id, $options){
  $params = array(
      'custom_group_id' => $group_id,
      'name' => str_replace(' ', '_', $title),
      'label' => $title,
      'data_type' => 'String',
      'html_type' => $options['html_type'],
      //      'default_value' => '20071212',
//      'weight' => 4,   
      'is_required' => 0,
      'is_searchable' => 0,
      'is_active' => 1,
      'version' => 3,
  );

  $params['text_length'] = 255;
  if (!empty($options['option_values'])) {
    $params['option_values'] = $options['option_values'];   
  } 
 
  $result = civicrm_api( 'custom_field','create',$params );

  return $result;
}

function get_custom_field_group_info($name) {

  $params = array(
      'version' => 3,
      'name' => str_replace(' ', '_', $name),
  );
  $result = civicrm_api('custom_group', 'get', $params);
  return $result;
}

function create_custom_field_group($title) {

  if (!empty($title)) {
    $params = array(
      'title' => $title,
//      'name'  => strtolower($title),
      'extends' => array('Contact'),
//      'weight' => $weight,
//      'collapse_display' => 1,
//      'style' => 'Inline',
//       'help_pre' => 'This is Pre Help For Test Group 1',
//       'help_post' => 'This is Post Help For Test Group 1',
      'is_active' => 1,
      'version' => 3,
    );
 
    $result = civicrm_api( 'custom_group','create',$params );
  }
  return $result;
}

I only just wrote this code. It does create fields, but it is not fully tested.

I hope this helps someone else. Please tell me what you think.
« Last Edit: April 18, 2012, 01:07:55 pm by druderman »

Matt2000

  • I post frequently
  • ***
  • Posts: 288
  • Karma: 27
    • http://www.ninjitsuweb.com
Re: Sample code to create custom groups and fields
April 18, 2012, 06:29:22 pm
Nice! Do you have some code to export fields in an existing installation to the configuration array format?
Drupal/CiviCRM micro-blogging http://twitter.com/matt2000

Ninjitsu Web Development http://www.NinjitsuWeb.com/

xavier

  • Forum Godess / God
  • I’m (like) Lobo ;)
  • *****
  • Posts: 4453
  • Karma: 161
    • Tech To The People
  • CiviCRM version: yes probably
  • CMS version: drupal
Re: Sample code to create custom groups and fields
April 18, 2012, 07:04:42 pm
Nice

bin/csv/import.php & bin/csv/export.php should be doing that too. On the last sprint, they fixed (not sure it applies to this case) so empty fields are not dropped - so the number of columns is constant.

X+
-Hackathon and data journalism about the European parliament 24-26 jan. Watch out the result

Erik Hommel

  • Forum Godess / God
  • I live on this forum
  • *****
  • Posts: 1773
  • Karma: 59
    • EE-atWork
  • CiviCRM version: all sorts
  • CMS version: Drupal
  • MySQL version: Ubuntu's latest LTS version
  • PHP version: Ubuntu's latest LTS version
Re: Sample code to create custom groups and fields
April 19, 2012, 12:10:04 am
Nice one, thanks for sharing!
Consultant/project manager at EEatWork and CiviCooP (http://www.civicoop.org/)

druderman

  • I’m new here
  • *
  • Posts: 24
  • Karma: 0
  • CiviCRM version: 4.1+
  • CMS version: Drupal 7
  • MySQL version: 5.0.77 and 5.1
  • PHP version: 5.2.13
Re: Sample code to create custom groups and fields
April 19, 2012, 06:31:57 am
Quote from: xavier on April 18, 2012, 07:04:42 pm

bin/csv/import.php & bin/csv/export.php should be doing that too. On the last sprint, they fixed (not sure it applies to this case) so empty fields are not dropped - so the number of columns is constant.


Ah, yes, I remember trying to get this to work a while back.
I couldn't figure out what parameters it wanted. And now the 4.1 version appears to take slightly different parameter than previous versions referenced in the forums, probably to support the v3 API.
Is there any documentation? Or good recent examples?

Using my 'brute force' code above, I need to export and import my customizations: mostly custom fields and values for contacts.
Some of the fields I have are text, multiselect, and date.
I have also written similar scripts using the API to update a multiselect i.e. to add a new option if it is not yet defined.

xavier

  • Forum Godess / God
  • I’m (like) Lobo ;)
  • *****
  • Posts: 4453
  • Karma: 161
    • Tech To The People
  • CiviCRM version: yes probably
  • CMS version: drupal
Re: Sample code to create custom groups and fields
April 19, 2012, 06:37:55 am
re csv, will check with jamie (next week probably) where we are on that+ new cli we were working on upgrading.

re 'brute force'. don't take me wrong, I'm all for the brutal approach and I recently wrote code to upgrade a long profile (60+fields) using this technique

X+
-Hackathon and data journalism about the European parliament 24-26 jan. Watch out the result

druderman

  • I’m new here
  • *
  • Posts: 24
  • Karma: 0
  • CiviCRM version: 4.1+
  • CMS version: Drupal 7
  • MySQL version: 5.0.77 and 5.1
  • PHP version: 5.2.13
Re: Sample code to create custom groups and fields
April 19, 2012, 07:09:47 am
Looking at the export.php code, I see it extends the cli.
So my best guess was to look at the doc for the cli, which unfortunately says 'deprecated'.

http://wiki.civicrm.org/confluence/display/CRMDOC41/Command-line+Script+Configuration+%28deprecated%29

And only just now, by looking at the doc, I can guess some of the syntax required for the command line.

This will export the first 25 contacts and stop. (Not sure why it stops at 25.)
Code: [Select]
php bin/csv/export.php -e contact -a get --output
This will output an empty array. For me type 4 is valid, so I'd hope it would return just the contacts I want.
Code: [Select]
php bin/csv/export.php -e contact -a get --contact_type=4 --output
Meanwhile, what I really want is the custom field descriptions.
Today, this method of exporting is a little too much trial and error for me.

xavier

  • Forum Godess / God
  • I’m (like) Lobo ;)
  • *****
  • Posts: 4453
  • Karma: 161
    • Tech To The People
  • CiviCRM version: yes probably
  • CMS version: drupal
Re: Sample code to create custom groups and fields
April 19, 2012, 07:20:59 am
Hi,
http://civicrm.org/blogs/xavier/api_batch_tools

same params as for the api, so if you want more than 25

rowcount=10000

and if you want custom fields return=first_name,last_name,custom_24

But as said, the 4.0 cli change broke it. Mostly FYI, for those on 3.4 or as soon as it's back
-Hackathon and data journalism about the European parliament 24-26 jan. Watch out the result

pgehres

  • I’m new here
  • *
  • Posts: 1
  • Karma: 0
  • CiviCRM version: 4.1.1
  • CMS version: Drupal6
  • MySQL version: 5.1.47-facebook-r3550-log Oh my, Facebook (r3550) 4.0-compat -Fi
  • PHP version: 5.3.2-2wm1
Re: Sample code to create custom groups and fields
April 30, 2012, 01:39:49 am
FYI for everyone who finds this thread, the bug Xavier mentions above can be found at:

issues.civicrm.org/jira/browse/CRM-9308

Pages: [1]
  • CiviCRM Community Forums (archive) »
  • Old sections (read-only, deprecated) »
  • Developer Discussion (Moderator: Donald Lobo) »
  • Sample code to create custom groups and fields

This forum was archived on 2017-11-26.