30 Awesome Drupal 7 API Functions

(You Should Already Know)

Created by Fredric Mitchell / @fredricmitchell

http://brightplumbox.com/30Drupal7API/

Assumptions

  1. Show Me the Code!
  2. Written something custom (familiar with PHP)
  3. You like using APIs
  4. Want to learn the "Drupal Way"
  5. Drupal as framework

Quick Intro

Paid Gig

Senior Developer at Phase2 Technology

Quick Intro

Passions

Drupal, DRY / KISS, Strat. Comm., Graphic Novels

Quick Intro

Learning

Javascript, Patience, Spanish

URL Shortcuts

Quick and easy ways to find API functions and Drupal projects.

d7, dp

Firefox

http://bit.ly/18XPrjF

Chrome

http://bit.ly/1dbB0eL

Strings

Print stuff.

t()

translate, sanitize

                            
$text = t(“@name's blog”, array('@name' => $value))
// Note: @name vs. %name vs. !name
                            
                        

l()

internal, external url

                            
$link = l(t('Link text'), 'node/34', array(
    'attributes' => array(
        'class' => array('about-link'),
    )
));
// Note: automatic alias replacement via url()
                            
                        

Rendering

Make stuff pretty.

drupal_render()

given render array, return HTML

                            
$render = array(
    'first_para' => array(
        '#type' => 'markup',
        '#markup' => 'A first paragraph',
    ),
    'second_para' => array(
        array('first item', 'second item', 'third item'),
            '#theme' => 'item_list',
    ),
);
return drupal_render($render);
                            
                        

Nodes

Store content, data.

node_load_multiple()

load nodes from db

                            
$nodes = node_load_multiple($nids = array())
// Note: calls entity_load(); statically cached
                            
                        

node_view()

a render array for given node

                            
                                $node = node_view($node, $view_mode);
                            
                        

node_view_multiple()

a render array of many nodes

                            
                                $nodes = node_view_multiple($nodes);
                            
                        

node_delete_multiple()

delete nodes from db

                            
                                node_delete_multiple($nids = array());
                            
                        

node_object_prepare()

prepare object for editing

                            
$node = new StdClass();

// Set type first.
$node->type = 'foobar';

node_object_prepare($node);
// Note: Current user will be set as uid.
                            
                        

node_save()

save a node to db

                            
node_save($node);
// Note: nothing is returned
                            
                        

Menus

Allow users to navigate to content, data.

hook_menu()

define menu items and callbacks

                            
function mymodule_menu() {
    $items['abc/def'] = array(
        'page callback' => 'mymodule_abc_view',
    );
    return $items;
}

function mymodule_abc_view($ghi = 0, $jkl = '') {
    // ...
}
                            
                        

menu_get_item()

get a router item

                            
$item = menu_get_item($path);
// Note: returns array defined in hook_menu()
                            
                        

menu_get_object()

load an object from router item

                            
$node = menu_get_object();
$type = $node->type;
// Note: Use instead of arg()
                            
                        

menu_tree_page_data()

get data for menu tree

                            
                                $tree = menu_tree_page_data('main-menu');
                            
                        

menu_tree_output()

return a menu tree render array

                            
// Build a HTML menu
$tree = menu_tree_page_data('main-menu');
$menu = menu_tree_output($tree, 1);
return drupal_render($menu);
                            
                        

Taxonomy

Categorize content, data.

taxonomy_vocabulary_machine_name_load()

get vocabulary by machine name

                            
// Get a taxonomy object.
$v = taxonomy_vocabulary_machine_name_load('vocab');
                            
                        

taxonomy_get_tree()

create hierarchy from vocab

                            
// Get a taxonomy object.
$v = taxonomy_vocabulary_machine_name_load('vocab');

// Build an array of taxonomy terms.
$terms = taxonomy_get_tree($v->vid);
foreach ($terms as $term) {
    $options[$term->tid] = $term->name;
}
                            
                        

Fields

Organize content, data at various pivot points.

field_info_field()

return array of field data

                            
// Get info a field name.
field_info_field('field_name');
                            
                        

field_info_instance()

return an array of field instance data

                            
// Get info on field name.
field_info_field('field_name');

// Get info on instance of field name from a bundle.
field_info_instance('node', 'field_name', 'article');
                            
                        

field_create_field()

creates a field

                            
// Note: Requires proper field / instance data array which you can get from a features export.

$field_bases = array();

// Exported field_base: 'field_sc_html'
$field_bases['field_sc_html'] = array(
    'active' => 1,
    'cardinality' => 1,
    'deleted' => 0,
    'entity_types' => array(),
    'field_name' => 'field_sc_html',
    'foreign keys' => array(
        'format' => array(
            'columns' => array(
                'format' => 'format',
            ),
            'table' => 'filter_format',
        ),
    ),
    'indexes' => array(
        'format' => array(
            0 => 'format',
        ),
    ),
    'locked' => 0,
    'module' => 'text',
    'settings' => array(),
    'translatable' => 0,
    'type' => 'text_long',
);
                            
                        

field_create_instance()

create instance of field, binding it to a bundle

                            
// Note: Requires proper field / instance data array which you can get from a features export.

$field_instances = array();

// Exported field_instance: 'bean-field_sc_html'
$field_instances['bean-field_sc_html'] = array(
    'bundle' => 'oms_sidebar_content',
    'default_value' => NULL,
    'deleted' => 0,
    'description' => '',
    'display' => array(
        'default' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 0,
        ),
    ),
    'entity_type' => 'bean',
    'field_name' => 'field_sc_html',
    'label' => 'HTML',
    'required' => 0,
    'settings' => array(
        'text_processing' => 1,
        'user_register_form' => FALSE,
    ),
    'widget' => array(
        'active' => 1,
        'module' => 'text',
        'settings' => array(
            'rows' => 5,
        ),
        'type' => 'text_textarea',
        'weight' => 2,
    ),
);
                            
                        

Bonus!

Using the field API functions

                            
function mymodule_install_fields($fields, $instance_fields, $type = 'node', $bundle) {
    foreach ($fields as $field) {
        // Create the field if it doesn't exist.
        if (!field_info_field($field['field_name'])) {
            field_create_field($field);
        }
    }
    unset($field);
    foreach ($instance_fields as $field) {
        if (!field_info_instance($type, $field['field_name'], $bundle)) {
            field_create_instance($field);
        }
    }
}
                            
                        

field_update_field()

update field

                            
// Update field details.
$field = field_info_field('field_name');
if (isset($my_condition)) {
    field_update_field($field);
}
                            
                        

field_update_instance()

updates field instance

                            
// Update field instance.
$instance = field_info_instance('node', $field_name, $bundle);
if ($instance) {
    field_update_instance($instance);
}
// Note: Can use in hook_update() to avoid UI config conflicts.
                            
                        

Alters

Change the assumptions.

drupal_alter()

passes variables to be changed

                            
$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
);

// Call all modules implementing hook_my_data_alter
drupal_alter('my_data', $data);

// Note: Use sparingly. hook_theme() is preferred for overriding styles.
                            
                        

hook_form_alter()

change a form before rendered

                            
function mymodule_form_alter(&$form, &$form_state) {
    $form['new_checkbox'] = array(
        '#type' => 'checkbox',
        '#title' => t ('Subscribe'),
    );
);
                            
                        

hook_form_FORM_ID_alter()

change a specific form by FORM ID before rendered

                            
function mymodule_form_node_form_alter() {
    ...
);
                            
                        

URLs

Grab the $_GET

drupal_get_query_parameters()

process url query

                            
// URL: http://mysite.com?text=foo&date=2013-09-14

$param = drupal_get_query_parameters();

// Values
// $param['text'] = foo
// $param['date'] = 2013-09-14
                            
                        

Paths

Where am I?

drupal_get_path()

returns path to a system item

                            
// Path to a file
$path = drupal_get_path('theme', 'mytheme') . '/mycustom.js';

// Include CSS or JS
drupal_add_js($path), array(
    'type' => 'file',
    'scope' => 'footer',
));

// Note: Also consider libraries_get_path()
                            
                        

module_load_include()

loads a module include file

                        
// Load node.admin.inc from the node module.
module_load_include('inc', 'node', 'node.admin');

// Load content_types.inc from the node module.
module_load_include('inc', 'node', 'content_types');
                        
                    

Querying Entities

Join ALL the tables!

EntityFieldQuery

a class to query entities

                            
// Query articles
$query = new EntityFieldQuery();

$query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'article')
    ->propertyCondition('status', 1);

$result = $query->execute();
$nids = array_keys($result['node']);
$nodes = node_load_multiple($nids);

// Note: EFQ presentation at http://bit.ly/top10efq
                            
                        

1 - 10

  • t()
  • l()
  • drupal_render()
  • entity_load()
  • node_load_multiple()
  • node_view()
  • node_view_multiple()
  • node_delete_multiple()
  • node_object_prepare()
  • node_save()

11 - 20

  • hook_menu()
  • menu_get_item()
  • menu_get_object()
  • menu_tree_page_data()
  • menu_tree_output()
  • taxonomy_get_tree()
  • taxonomy_vocabulary_machine_name_load()
  • field_info_field()
  • field_info_instance()
  • field_create_field()

21 - 30

  • field_create_instance()
  • field_update_field()
  • field_update_instance()
  • drupal_alter()
  • hook_form_alter()
  • hook_form_FORM_ID_alter()
  • drupal_get_query_parameters()
  • drupal_get_path()
  • module_load_include()
  • EntityFieldQuery

Questions?

By Fredric Mitchell / @fredricmitchell

Slides: http://brightplumbox.com/30Drupal7API/

Slides Repo: https://github.com/fmitchell/30Drupal7API

Feedback: joind.in/talk/view/10311