Creating a module on Drupal, quick start
Let's start with api.drupal.org. Open the page for the hook_node_validate() hook, which is triggered before a node is saved:
http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_validate/7
Hooks allow us to inject our custom code into the normal Drupal process—adding validations, data fields, form elements, etc.
Let's add our custom module to the sites/all/modules
directory:
sites/all/modules/custom/ sites/all/modules/custom/custom.info sites/all/modules/custom/custom.module
Inside the custom.info
file, write the following:
name = Custom description = Custom core = 7.x
In the custom.module
file, we’ll implement a validation that ensures the body field of a node is not empty. If it is, we display an error. (Of course, this could be enforced in the field settings as well, but this is for demonstration purposes.):
custom.module
body['und'][0]['value'])) { form_set_error('node-body', 'Body is empty'); // Displays error and prevents the node from being saved } }
In this case, when the site language is only one (undefined or und
), we check the first textarea
of the body field. (It’s possible to configure multiple textareas per field.)
Use the Devel module and its dsm()
function to print debug messages and inspect arrays or objects on screen:
?>