I have written modules before where I define fields in hook_form(), but this time I want to add CCK fields to my custom content type (programatically on install) , I am having a hard time finding information on this.

Drupal 6

Comments

sunnydeveloper’s picture

So...this is what I did in case someone is interested, or wants to disagree.

I created a dummy content type and the fields I needed for my module. I then used the CCK Export to export those fields (this gives you the code you'll need to create them dynamically).

Then I did what this page outlined:

http://drewish.com/node/118 using content_field_instance_create($field); for my content type.

tmsimont’s picture

To do this you'll need to utilize hook_install() and then you should probably use hook_uninstall() as well.

In my case I was creating fields for a content type called "accordionslider_slide"

See this example accordionslider.install file, which complements my node definition in an accordionslider.module file:


function accordionslider_install(){
	module_load_include("inc", "accordionslider", "accordionslider.fields");
	module_load_include('inc', 'content', 'includes/content.crud');
	$fields = _accordionslider_get_fields();
	foreach($fields as $field){
		$field['type_name'] = 'accordionslider_slide';
		content_field_instance_create($field);
	}
}

function accordionslider_uninstall(){
	module_load_include("inc", "accordionslider", "accordionslider.fields");
	module_load_include('inc', 'content', 'includes/content.crud');
	$fields = _accordionslider_get_fields();
	foreach($fields as $field){
		$field['type_name'] = 'accordionslider_slide';
		content_field_instance_delete($field['field_name'], $type_name, FALSE);
	}
    content_clear_type_cache(TRUE);
	menu_rebuild();
}

Note that I defined the function _accordionslider_get_fields() inside a file called accordionslider.fields.inc.
The definition for my fields came from the export command (via content copy module) as tiptoes described to do above.

rpeters’s picture

How would you do this in Drupal 7?