21st September
2008
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:
-
/**
-
* Programmatically create CCK fields and types using the content copy module
-
* @param $type string
-
* content type to create, defaults to new type, if type exists, only fields will be added
-
* @param $macro array
-
* exported array from content types -> export. If file is not specified, macro will be used
-
* @param $file string
-
* path to file containing content copy exported macro data structure. no escaping needed.
-
*/
-
function base_create_content($type = '', $macro = '', $file = '') {
-
if(!module_exists("content_copy")){
-
drupal_set_message('Programmatically creating CCK fields requires the Content Copy module. Exiting.');
-
return;
-
}
-
$values['type_name'] = $type;
-
//get macro import data, prefer file first
-
if($file){
-
}else{
-
drupal_set_message('Unable to read input file for import. Exiting.');
-
return;
-
}
-
}elseif($macro){
-
$values['macro'] = $macro;
-
}
-
//include required files
-
include_once './'. drupal_get_path('module', 'node') .'/content_types.inc';
-
include_once('./'. drupal_get_path('module', 'content') .'/content_admin.inc');
-
//import content by executing content copy import form and passing macro
-
drupal_execute("content_copy_import_form", $values);
-
}
I then call it like:
PHP:
-
//use absolute path to include file
-
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.
This is a blog to record tidbits of information. It documents thoughts and ideas that may be useful for other people, like yourself.