Adding Custom Fields to a Custom Content Type in Drupal 7

Creating a custom content type without any fields isn’t really useful. Fortunately, defining your own custom fields and attaching them to your custom content type is built into Drupal 7. For Drupal 6, you have to use the CCK module.

1. Create your custom content type

First off, you need to define a custom content type in your module.

2. Implement hook_node_type_insert()

hook_node_type_insert() allows us to hook into when a new content type is being created. Since we are creating a new content type in step 1, we can define our new fields here. For each of our fields, we define a field and create an instance of the field to tie it to our content type. It is useful to define private functions that contain the definitions for both the fields and instances.

/**
 * Implements hook_node_type_insert().
 */
function mymodule_node_type_insert($content_type) {
	// Make sure to only perform operations on the type we want.
	if($content_type->type == 'my_new_type') {
		// Add the body field.
		node_add_body_field($content_type, t('Description'));
		// Create all the fields we are adding to our content type.
		foreach(_mymodule_installed_fields() as $field) {
			field_create_field($field);
		}
		// Create all the instances for our fields.
		foreach(_mymodule_installed_instances() as $instance) {
			field_create_instance($instance);
		}
	}
}

/**
 * Defines the list of fields.
 * @returns
 */
function _mymodule_installed_fields() {
	$fields = array();

	// Field definition for our custom URL field.
	$fields['field_url'] = array(
		'field_name' => 'field_url',
		'type' => 'text',
		'cardinality' => 1,
	);

	return $fields;
}

/**
 * Defines the list of field instances.
 * @returns
 */
function _mymodule_installed_instances() {
	$instances = array();

	$instances['field_url'] = array(
		'field_name' => 'field_url',
		'entity_type' => 'node',
		'bundle' => 'mymodule',
		'label' => t('URL'),
		'required' => true,
	);

	return $instances;
}

After reinstalling your module, you will now see your new field on your content type.

2 thoughts on “Adding Custom Fields to a Custom Content Type in Drupal 7

  1. Kenyon Johsnton Reply

    Hey Mirza, great tutorial, but I’m having issues with my custom fields, they just don’t show up in the installation. The body and subject fields show, but not my custom fields. I followed your instructions exactly.

    Any thoughts?

    • Mirza Busatlic Post authorReply

      Hi Kenyon,
      Did you specify the ‘bundle’ (line #47) attribute appropriately? It needs to reference the name of your module.

Leave a Reply

Your email address will not be published. Required fields are marked *