Example: Node

  1. drupal
    1. 8
    2. 6
    3. 7

Example defining a node type in code.

This is an example outlining how a module can be used to define a new node type. Our example node type will allow users to specify multiple "colors", a "quantity" and an "image" for their nodes; some kind of rudimentary inventory-tracking system, perhaps?

The basic pattern for defining a node type is to tell Drupal about the node's field types, and view modes. Drupal will then take over and manage the storage for this node type. This differs from Drupal 6, where we would have to handle all the database storage ourselves in the module.

Remember that most node types do not require any custom code, as one simply creates them using the Drupal user interface. Creating a node like this in code is a special case.

Since we only have to define our node type once, most of the code required to do this is moved to the node type's .install file. Drupal 7 has us defining most of our node structure in arrays, and passing those to node_type_save(). We use hook_install() as a convenient place to define these types, and hook_uninstall() as a convenient place to not only uninstall the data contained in these nodes, but also remove the node types from Drupal's knowledge.

In previous versions of Drupal, "teaser" and "page" were node view modes. In Drupal 7 we can define custom view modes to let the node know how it should return it's data. This module declares a custom view mode called "example_node_list".

Consult the Field API Tutorial and Field API Handbook Page and Field API documentation.

See also



Functions & methods

node_example_entity_info_alterImplements hook_entity_info_alter().
node_example_field_formatter_infoImplements hook_field_formatter_info().
node_example_field_formatter_viewImplements hook_field_formatter_view().
node_example_helpImplements hook_help().
node_example_installImplements hook_install().
node_example_menuImplements hook_menu().
node_example_pageCallback that builds our content and returns it to the browser.
node_example_themeImplements hook_theme().
node_example_uninstallImplements hook_uninstall().
theme_example_node_colorA custom theme function.
_node_example_installed_fieldsReturns a structured array defining the fields created by this content type.
_node_example_installed_instancesReturns a structured array defining the instances for this content type.

examples/node_example/node_example.module, line 10