SlideShare une entreprise Scribd logo
1  sur  31
LEARNING THE BASICS
 OF THE DRUPAL API
      Badiu Alexandru




     Drupalcamp Bucharest 2011
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
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
MODULES
•   Modules are the building blocks
•   name.info
•   name.module
•   sites/all/modules



            Drupalcamp Bucharest 2011
MODULES
•   Create blocks
•   Create content types
•   Create pages and forms
•   Augment Drupal core
•   Augment Drupal modules


            Drupalcamp Bucharest 2011
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
DCAMP.M
•   dcamp.info

      name = DrupalCamp Forward
      description = Drupalcamp D7 Demo
      package = Drupalcamp
      version = 1.0
      core = 7.x
      files[] = dcamp.module




             Drupalcamp Bucharest 2011
DCAMP.M
•   dcamp.module
•   Is a php file
•   Contains the module code
•   Implements hooks



             Drupalcamp Bucharest 2011
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
HOOKS
•   hook_name
•   function dcamp_name($arg1, $arg2)
    {...}




            Drupalcamp Bucharest 2011
HOOKS
•   http://api.drupal.org/api/drupal/
    includes--module.inc/group/hooks/
    7
•   Lots of them
•   Block, Node, Forms, Images, Menus,
    Taxonomy, Permissions, Users


            Drupalcamp Bucharest 2011
BLOCK
•   hook_block_info
•   hook_block_view
•   function dcamp_block_info()
•   function dcamp_block_view($delta =
    ‘’)


            Drupalcamp Bucharest 2011
BLOCK
function dcamp_block_info() {
  $blocks = array(
     'forward_block' => array(
       'info' => t('Forward node block'),
       'cache' => DRUPAL_CACHE_PER_ROLE
     )
  );
  return $blocks;
}

function dcamp_block_view($delta = '') {
  $block = array(
     'subject' => t('Spread the word'),
     'content' => 'Block contents.'
  );
  return $block;
}

                  Drupalcamp Bucharest 2011
BLOCK
•   The block appears on every page
•   We want to limit it to roles via
    permissions
•   We want to limit it to nodes



             Drupalcamp Bucharest 2011
PERMISSIO
•   hook_permission
•   Returns an array of permissions
•   user_access($perm) checks
function dcamp_permission() {
  return array(
     'forward node' => array(
        'title' => t('Forward nodes to friends')
     ),
  );
}


                   Drupalcamp Bucharest 2011
PERMISSIO
function dcamp_block_content() {
  if (!user_access('forward node')) {
    return '';
  }

    return "Block content.";
}




                    Drupalcamp Bucharest 2011
LIMITING
•   Internal Drupal path: node/4
•   Path alias: page/about-us.html
•   arg(0) = node, arg(1) = 4
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
}
else {
  return '';
}

                  Drupalcamp Bucharest 2011
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
FORMS
•   Form generation: dcamp_form
•   Form validation:
    dcamp_form_validate
•   Form submit: dcamp_form_submit



           Drupalcamp Bucharest 2011
FORM
function dcamp_form($form, $form_state, $nid) {
  $form = array();

    $form['nid'] = array(
      '#type' => 'hidden',
      '#value' => $nid,
    );

    $form['email'] = array(
      '#type' => 'textfield',
      '#title' => t('Email address'),
      '#size' => 25,
      '#required' => TRUE
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Forward')
    );

    return $form;
}
                        Drupalcamp Bucharest 2011
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
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
SENDING
•   Complicated
•   Requires implementing a hook -
    hook_mail
•   Different email types
•   Of course, you can just use mail()


             Drupalcamp Bucharest 2011
SENDING
function dcamp_mail($key, &$message, $params) {
  if ($key == 'forward') {
    $langcode = $message['language']->language;
    $message['subject'] = t('Recommended site', array(),
array('langcode' => $langcode));
    $message['body'][] = t("You've been recommended this !
url.", array('!url' => url('node/' . $params['nid'],
array('absolute' => TRUE))), array('langcode' => $langcode));
  }
}


drupal_mail('dcamp', 'forward', $email,
user_preferred_language($user), array('nid' => $nid));




                  Drupalcamp Bucharest 2011
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
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
MENU
•   Url:
    •   admin/config/content/forward
    •   wildcards: node/%/forward
•   Title
•   Description
•   Type: Normal, Tab, Callback

              Drupalcamp Bucharest 2011
MENU
•   Page callback
•   Page arguments
•   Access callback
•   Access arguments



            Drupalcamp Bucharest 2011
SAVING
•   You could use the database
•   variable_set(‘variable’, $value);
•   Works with arrays and objects too
•   variable_get(‘variable’,
    $default_value);


             Drupalcamp Bucharest 2011
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
THANK
   andu@ctrlz.ro
   http://ctrlz.ro




Drupalcamp Bucharest 2011

Contenu connexe

Tendances

Drupal Step-by-Step: How We Built Our Training Site, Part 1
Drupal Step-by-Step: How We Built Our Training Site, Part 1Drupal Step-by-Step: How We Built Our Training Site, Part 1
Drupal Step-by-Step: How We Built Our Training Site, Part 1
Acquia
 

Tendances (20)

Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
 
Drupal Step-by-Step: How We Built Our Training Site, Part 1
Drupal Step-by-Step: How We Built Our Training Site, Part 1Drupal Step-by-Step: How We Built Our Training Site, Part 1
Drupal Step-by-Step: How We Built Our Training Site, Part 1
 
Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019
 
Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes
 
Drupal Camp Porto - Developing with Drupal: First Steps
Drupal Camp Porto - Developing with Drupal: First StepsDrupal Camp Porto - Developing with Drupal: First Steps
Drupal Camp Porto - Developing with Drupal: First Steps
 
Geodaten & Drupal 7
Geodaten & Drupal 7Geodaten & Drupal 7
Geodaten & Drupal 7
 
Modularity and Layered Data Model
Modularity and Layered Data ModelModularity and Layered Data Model
Modularity and Layered Data Model
 
A Short Introduction To jQuery
A Short Introduction To jQueryA Short Introduction To jQuery
A Short Introduction To jQuery
 
Let's write secure drupal code! - Drupal Camp Pannonia 2019
Let's write secure drupal code! - Drupal Camp Pannonia 2019Let's write secure drupal code! - Drupal Camp Pannonia 2019
Let's write secure drupal code! - Drupal Camp Pannonia 2019
 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupal
 
Андрей Юртаев - Improve theming with (Twitter) Bootstrap
Андрей Юртаев - Improve theming with (Twitter) BootstrapАндрей Юртаев - Improve theming with (Twitter) Bootstrap
Андрей Юртаев - Improve theming with (Twitter) Bootstrap
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Image manipulation in WordPress 3.5
Image manipulation in WordPress 3.5Image manipulation in WordPress 3.5
Image manipulation in WordPress 3.5
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
Any tutor
Any tutorAny tutor
Any tutor
 
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
 
Jquery introduction
Jquery introductionJquery introduction
Jquery introduction
 
Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
Development Approach
Development ApproachDevelopment Approach
Development Approach
 

Similaire à Learning the basics of the Drupal API

Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)
Reinout van Rees
 

Similaire à Learning the basics of the Drupal API (20)

What's new in the Drupal 7 API?
What's new in the Drupal 7 API?What's new in the Drupal 7 API?
What's new in the Drupal 7 API?
 
Fapi
FapiFapi
Fapi
 
Drupal Module Development - OSI Days 2010
Drupal Module Development - OSI Days 2010Drupal Module Development - OSI Days 2010
Drupal Module Development - OSI Days 2010
 
Drupal Module Development
Drupal Module DevelopmentDrupal Module Development
Drupal Module Development
 
Advanced moduledevelopment d6_slideshare
Advanced moduledevelopment d6_slideshareAdvanced moduledevelopment d6_slideshare
Advanced moduledevelopment d6_slideshare
 
Debugging in drupal 8
Debugging in drupal 8Debugging in drupal 8
Debugging in drupal 8
 
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptjQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
Getting Started with DrupalGap
Getting Started with DrupalGapGetting Started with DrupalGap
Getting Started with DrupalGap
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practices
 
Convert modules from 6.x to 7.x
Convert modules from 6.x to 7.xConvert modules from 6.x to 7.x
Convert modules from 6.x to 7.x
 
Drupal, Android and iPhone
Drupal, Android and iPhoneDrupal, Android and iPhone
Drupal, Android and iPhone
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
Drupal Security from Drupalcamp Bratislava
Drupal Security from Drupalcamp BratislavaDrupal Security from Drupalcamp Bratislava
Drupal Security from Drupalcamp Bratislava
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
Drupal vs WordPress
Drupal vs WordPressDrupal vs WordPress
Drupal vs WordPress
 
Routing in Drupal 8
Routing in Drupal 8Routing in Drupal 8
Routing in Drupal 8
 
Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)Django class based views (Dutch Django meeting presentation)
Django class based views (Dutch Django meeting presentation)
 

Plus de Alexandru Badiu

Plus de Alexandru Badiu (12)

Behavior Driven Development with Drupal
Behavior Driven Development with DrupalBehavior Driven Development with Drupal
Behavior Driven Development with Drupal
 
Drupal 8
Drupal 8Drupal 8
Drupal 8
 
Drupal as a first class mobile platform
Drupal as a first class mobile platformDrupal as a first class mobile platform
Drupal as a first class mobile platform
 
Cloud to the rescue? How I learned to stop worrying and love the cloud
Cloud to the rescue? How I learned to stop worrying and love the cloudCloud to the rescue? How I learned to stop worrying and love the cloud
Cloud to the rescue? How I learned to stop worrying and love the cloud
 
REST Drupal
REST DrupalREST Drupal
REST Drupal
 
Cloud to the rescue? How I learned to stop worrying and love the cloud
Cloud to the rescue? How I learned to stop worrying and love the cloudCloud to the rescue? How I learned to stop worrying and love the cloud
Cloud to the rescue? How I learned to stop worrying and love the cloud
 
Using Features
Using FeaturesUsing Features
Using Features
 
Publish and Subscribe
Publish and SubscribePublish and Subscribe
Publish and Subscribe
 
Using Features
Using FeaturesUsing Features
Using Features
 
Concepte de programare functionala in Javascript
Concepte de programare functionala in JavascriptConcepte de programare functionala in Javascript
Concepte de programare functionala in Javascript
 
Drupal and Solr
Drupal and SolrDrupal and Solr
Drupal and Solr
 
Prezentare Wurbe
Prezentare WurbePrezentare Wurbe
Prezentare Wurbe
 

Dernier

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Dernier (20)

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

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
  • 5. MODULES • Create blocks • Create content types • Create pages and forms • Augment Drupal core • Augment Drupal 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
  • 7. DCAMP.M • dcamp.info name = DrupalCamp Forward description = Drupalcamp D7 Demo package = Drupalcamp version = 1.0 core = 7.x files[] = dcamp.module 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
  • 10. HOOKS • hook_name • function dcamp_name($arg1, $arg2) {...} Drupalcamp Bucharest 2011
  • 11. HOOKS • http://api.drupal.org/api/drupal/ includes--module.inc/group/hooks/ 7 • Lots of them • Block, Node, Forms, Images, Menus, Taxonomy, Permissions, Users Drupalcamp Bucharest 2011
  • 12. BLOCK • hook_block_info • hook_block_view • function dcamp_block_info() • function dcamp_block_view($delta = ‘’) Drupalcamp Bucharest 2011
  • 13. BLOCK function dcamp_block_info() { $blocks = array( 'forward_block' => array( 'info' => t('Forward node block'), 'cache' => DRUPAL_CACHE_PER_ROLE ) ); return $blocks; } function dcamp_block_view($delta = '') { $block = array( 'subject' => t('Spread the word'), 'content' => 'Block contents.' ); return $block; } Drupalcamp Bucharest 2011
  • 14. BLOCK • The block appears on every page • We want to limit it to roles via permissions • We want to limit it to nodes Drupalcamp Bucharest 2011
  • 15. PERMISSIO • hook_permission • Returns an array of permissions • user_access($perm) checks function dcamp_permission() { return array( 'forward node' => array( 'title' => t('Forward nodes to friends') ), ); } Drupalcamp Bucharest 2011
  • 16. PERMISSIO function dcamp_block_content() { if (!user_access('forward node')) { return ''; } return "Block content."; } Drupalcamp Bucharest 2011
  • 17. LIMITING • Internal Drupal path: node/4 • Path alias: page/about-us.html • arg(0) = node, arg(1) = 4 if (arg(0) == 'node' && is_numeric(arg(1))) { $nid = arg(1); } else { return ''; } 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
  • 20. FORM function dcamp_form($form, $form_state, $nid) { $form = array(); $form['nid'] = array( '#type' => 'hidden', '#value' => $nid, ); $form['email'] = array( '#type' => 'textfield', '#title' => t('Email address'), '#size' => 25, '#required' => TRUE ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Forward') ); return $form; } 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
  • 24. SENDING function dcamp_mail($key, &$message, $params) { if ($key == 'forward') { $langcode = $message['language']->language; $message['subject'] = t('Recommended site', array(), array('langcode' => $langcode)); $message['body'][] = t("You've been recommended this ! url.", array('!url' => url('node/' . $params['nid'], array('absolute' => TRUE))), array('langcode' => $langcode)); } } drupal_mail('dcamp', 'forward', $email, user_preferred_language($user), array('nid' => $nid)); 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
  • 27. MENU • Url: • admin/config/content/forward • wildcards: node/%/forward • Title • Description • Type: Normal, Tab, Callback Drupalcamp Bucharest 2011
  • 28. MENU • Page callback • Page arguments • Access callback • Access arguments 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
  • 31. THANK andu@ctrlz.ro http://ctrlz.ro Drupalcamp Bucharest 2011

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n