Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Learning the basics of the Drupal API
1. LEARNING THE BASICS
OF THE DRUPAL API
Badiu Alexandru
Drupalcamp Bucharest 2011
2. THIS
• We’re going to use Drupal 7
• For beginners, intended as a
continuation of “From zero to hero”
• Going to assume you know basic
concepts such as blocks and nodes
Drupalcamp Bucharest 2011
3. YOU’LL
• The basics of module development
• How to create blocks
• How to check for permissions
• How to create forms
• How to create menu items
• How to send email
Drupalcamp Bucharest 2011
4. MODULES
• Modules are the building blocks
• name.info
• name.module
• sites/all/modules
Drupalcamp Bucharest 2011
6. DCAMP.M
• DrupalCamp Forward
• Allows a user to forward a node url
to a friend
• Displays a block on each node page
• Can appear only on specific node
types
Drupalcamp Bucharest 2011
8. DCAMP.M
• dcamp.module
• Is a php file
• Contains the module code
• Implements hooks
Drupalcamp Bucharest 2011
9. HOOKS
• Hooks are callbacks
• Everytime an action is performed in
Drupal a specific hook is called
• You can alter the action data
• You can do unrelated things
Drupalcamp Bucharest 2011
18. FORMS
• Forms are generated via a structured
array of elements
• They have an ID which is the
function that returns the structure
• drupal_get_form(‘dcamp_form’)
returns the form HTML
Drupalcamp Bucharest 2011
19. FORMS
• Form generation: dcamp_form
• Form validation:
dcamp_form_validate
• Form submit: dcamp_form_submit
Drupalcamp Bucharest 2011
21. FORM
• $form_state[‘values’]
• form_set_error
function dcamp_form_validate($form, &$form_state) {
$email = $form_state['values']['email'];
if (!valid_email_address($email)) {
form_set_error('email', t('Please enter a valid email
address.'));
}
}
Drupalcamp Bucharest 2011
22. FORM
function dcamp_form_submit($form, &$form_state) {
global $user;
$email = $form_state['values']['email'];
$nid = $form_state['values']['nid'];
// send an email with the url to the email address
drupal_set_message(t('The node has been forwarded to
%email.', array('%email' => $email)));
}
Drupalcamp Bucharest 2011
23. SENDING
• Complicated
• Requires implementing a hook -
hook_mail
• Different email types
• Of course, you can just use mail()
Drupalcamp Bucharest 2011
25. ADMIN
• We want an admin page
• admin/config/content/forward
• Another hook (no surprise there)
• hook_menu
• We’ll use a form
Drupalcamp Bucharest 2011
26. MENU
• Every page in a Drupal site is a menu
item
• Does not mean it has to appear in
the site menu
Drupalcamp Bucharest 2011
29. SAVING
• You could use the database
• variable_set(‘variable’, $value);
• Works with arrays and objects too
• variable_get(‘variable’,
$default_value);
Drupalcamp Bucharest 2011
30. RESOURCE
• Read other people’s code
• http://api.drupal.org
• Pro Drupal 7 Development
• Examples - http://
drupalexamples.info/
• Textmate Bundle and alternatives
Drupalcamp Bucharest 2011