Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Create New Content Type Programmatically in Drupal 7?

I'm building a module (my_module) in Drupal 7.

It has some functionality and also will create new content type.

In my_module.install I implemented the hook_install (my_module_install).

Can I use more one implementation of hook_install to create new content type (my_cck_install) in this module?

If (yes), how should I do this?

Else: have I do this in another module? :-)

like image 423
alsator Avatar asked Nov 14 '11 07:11

alsator


2 Answers

You can't use more than one implementation of hook_install in the same module; in PHP you can't have 2 function with the same name which rules this out.

You would just need to add your new content type in the same hook_install anyway (have a look at how the standard installation profile does it at /profiles/standard/standard.install). This is how I always add new content types from the install file (using the example of a testimonials module):

function testimonial_install() {
  // Make sure a testimonial content type doesn't already exist
  if (!in_array('testimonial', node_type_get_names())) {
    $type = array(
      'type' => 'testimonial',
      'name' => st('Testimonial'),
      'base' => 'node_content',
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
      'title_label' => 'Customer / Client Name'
    );

    $type = node_type_set_defaults($type);
    node_type_save($type);
    node_add_body_field($type);
  }
}
like image 160
Clive Avatar answered Oct 11 '22 13:10

Clive


The following code will create a content type called "Event" with a machine name of 'event' and a title field -

//CREATE NEW CONTENT TYPE
function orderform_node_info() {
  return array(
    'event' => array(
    'name' => t('Event'),
    'base' => 'event',
    'description' => t('A event content type'),
    'has_title' => TRUE
    ),
  );
}


function event_form($node,$form_state) {
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('event Title'),
    '#default_value' => !empty($node->title) ? $node->title : '',
    '#required' => TRUE,
    '#weight' => -5
  );
  return $form;
}
//END CONTENT TYPE

you should place it in your .module file... if you want do add additional fields to it, let me know and I'll patch you up with the code... good luck!

like image 31
DataB Avatar answered Oct 11 '22 14:10

DataB