Main image
21st September
2008
written by david

I recently needed to programmatically create CCK fields for a custom module.
I wanted to be able to install my module and automatically create it's required CCK fields.
I ended up using the following code function:

PHP:
  1. /**
  2. * Programmatically create CCK fields and types using the content copy module
  3. * @param $type string
  4. * content type to create, defaults to new type, if type exists, only fields will be added
  5. * @param $macro array
  6. * exported array from content types -> export. If file is not specified, macro will be used
  7. * @param $file string
  8. * path to file containing content copy exported macro data structure. no escaping needed.
  9. */
  10. function base_create_content($type = '', $macro = '', $file = '') {
  11.   if(!module_exists("content_copy")){
  12.     drupal_set_message('Programmatically creating CCK fields requires the Content Copy module. Exiting.');
  13.     return;
  14.   }
  15.   $values = array();
  16.   $values['type_name'] = $type;
  17.   //get macro import data, prefer file first
  18.   if($file){
  19.     if(file_exists($file)){
  20.       $values['macro'] = file_get_contents($file);
  21.     }else{
  22.       drupal_set_message('Unable to read input file for import. Exiting.');
  23.       return;
  24.     }
  25.   }elseif($macro){
  26.     $values['macro'] = $macro;
  27.   }
  28.   //include required files
  29.   include_once './'. drupal_get_path('module', 'node') .'/content_types.inc';
  30.   include_once('./'. drupal_get_path('module', 'content') .'/content_admin.inc');
  31.   //import content by executing content copy import form and passing macro
  32.   drupal_execute("content_copy_import_form", $values);
  33. }

I then call it like:

PHP:
  1. //use absolute path to include file
  2. base_create_content($type = 'my_type', $macro = '', $file = realpath('.') . '/sites/all/modules/my_module/cck/fields.inc');

where fields.inc contains the exported macro from admin > content types > export and my_module defines the my_type type in hook_node_info. You could also make 'my_type' into '' and create a new type.


Leave a reply