Drupal cheat sheet

Over the years, we compiled quite a bit of source code bits in our blog. This is the result! If you are a developer, you'll love. If you are not a developer - let's call em *geeks*.

Links

http://api.drupal.org
http://api.drupal.org/api/drupal/developer--topics--forms_api_reference....
http://api.drupal.org/api/drupal/developer--topics--forms_api_reference....

Snippets

Manually set path auto paths - in nodeapi op=update, insert

<?php
if(module_exists('pathauto')) {
  _pathauto_include();
  $origPath = 'node/' . $node->nid;
  $terms = taxonomy_node_get_terms_by_vocabulary($node, 1);
  $term = array_shift($terms);
  $title = str_replace('ä', 'ae', $node->title);
  $title = str_replace('ü', 'ue', $title);
  $title = str_replace('ö', 'oe', $title);
  $title = str_replace('!', '', $title);
  $pathAlias = pathauto_cleanstring(str_replace('>', '', $term->name), true) . '/' . pathauto_cleanstring($title, true);
  path_set_alias($origPath, $pathAlias, null);
}
?>

Image Cache Usage

print theme('imagecache', $preset, $image['filepath'], $alt, $title, $attributes);

Manually load a bunch of nodes with SQL

$nodes = array();
$sql = "SELECT nid FROM content_type_event";
$result = db_query($sql);
while ($result &amp;&amp; ($object = db_fetch_object($result))) {
  $nodes[] = node_load($object-&gt;nid);
}

Manually load a menu

$menu_global = menu_navigation_links("secondary-links", 0); $menu1 = menu_navigation_links("primary-links", 0); print theme('links', $menu1, array('class' =&gt; 'links_primary-links'));

Add a javascript

drupal_add_js(drupal_get_path('theme', 'garland').'/custom.js');

Get the nice url alias from raw path

drupal_get_path_alias('/node/'.$node-&gt;nid, $language-&gt;language);

Manually filter text

$output_blogentry .= _filter_url(_filter_autop(($node-&gt;field_blog_content[0]['value'])), 2).'

Programmatically output CCK node form

$node = new stdClass(); $node-&gt;type = 'blog'; $node-&gt;uid = $user-&gt;uid; $node-&gt;name = $user-&gt;name; // Important! module_load_include('inc', 'node', 'node.pages'); $output .= drupal_get_form('blog_node_form', $node);

Form alter example

function custom_form_alter(&amp;$form, $form_state, $form_id) { switch ($form_id) { case "search_form" : //debug($form); unset($form['title']); // unset the title break; } }

Node Api Example

function hook_nodeapi(&amp;$node, $op, $a3 = NULL, $a4 = NULL) { switch ($op) { case 'presave': if ($node-&gt;nid &amp;&amp; $node-&gt;moderate) { // Reset votes when node is updated: $node-&gt;score = 0; $node-&gt;users = ''; $node-&gt;votes = 0; } break; case 'insert': case 'update': if ($node-&gt;moderate &amp;&amp; user_access('access submission queue')) { drupal_set_message(t('The post is queued for approval')); } elseif ($node-&gt;moderate) { drupal_set_message(t('The post is queued for approval. The editors will decide whether it should be published.')); } break; case 'view': $node-&gt;content['my_additional_field'] = array( '#value' =&gt; theme('mymodule_my_additional_field', $additional_field), '#weight' =&gt; 10, ); break; } } ?&gt; Additional documentation: http://api.drupal.org/api/function/hook_nodeapi // TERMS BY NODE AND VOC $terms = taxonomy_node_get_terms_by_vocabulary($node, 2); // TERMS BY NODE $terms = taxonomy_node_get_terms($node); theme_views_view_unformatted__VIEWNAME($view, $options, $rows, $title); theme_views_view_list__VIEWNAME($view, $options, $rows, $title); theme_views_view_grid__VIEWNAME($view, $options, $rows, $title); theme_views_view_table__VIEWNAME($view, $options, $rows, $title); theme_views_view_summary__VIEWNAME($view, $options, $rows, $title); theme_views_view_summary_unformatted__VIEWNAME($view, $options, $rows, $title); theme_views_view_rss__VIEWNAME($view, $options, $rows, $title); //Individual item theming: theme_views_view_row_comment__VIEWNAME($view, $options, $row); theme_views_view_row_node__VIEWNAME($view, $options, $row); theme_views_view_row_search__VIEWNAME($view, $options, $row); theme_views_view_row_fields__VIEWNAME($view, $options, $row); //And special theming functions for: theme_views_exposed_form__VIEWNAME ( $form ); theme_views_more__VIEWNAME($more_url); function customnewsletter_menu() { $items = array(); $items['admin/customnewsletter'] = array( 'title' =&gt; 'Newsletter', 'access arguments' =&gt; array('admnister content'), 'type' =&gt; MENU_DEFAULT_LOCAL_TASK, 'page callback' =&gt; 'customnewsletter_page_newsletters', ); $items['admin/customnewsletter/%/test'] = array( 'title' =&gt; 'Newsletter', 'access arguments' =&gt; array('admnister content'), 'page arguments' =&gt; array(2), 'page callback' =&gt; 'customnewsletter_test', ); $items['admin/customnewsletter/%/send'] = array( 'title' =&gt; 'Newsletter senden', 'access arguments' =&gt; array('admnister content'), 'page arguments' =&gt; array(2), 'page callback' =&gt; 'customnewsletter_send', ); return $items; }

Views programmatically

Drupal6 views_include('view'); $view = view::load('newsticker'); $view-&gt;execute(); return print_r($view-&gt;result, true); or $output .= views_embed_view('viewname', 'default', $user-&gt;uid); http://groups.drupal.org/node/10129

page template depending on parameters

function custom_preprocess_page(&amp;$vars) { if (arg(0)=='reservation') { $vars['template_files'] = array('page-iframe'); } if (arg(0)=='ajax') { $vars['template_files'] = array('page-ajax'); } } http://api.drupal.org/api/function/template_preprocess_page/6 http://drupal.org/node/249726

form _validate _submit functions

Drupal 6 drupal_get_form(myname_form, $my_param1, $my_param2); function myname_form($form_state, $my_param1, $my_param2) { } function myname_form_validate($form, &amp;$form_state) { } function myname_form_submit($form, &amp;$form_state) { } Drupal 5 drupal_get_form(myname_form); function myname_form() { } function myname_form_validate($form_id, $form_values) { } function myname_form_submit($form_id, $form_values) { }

create node programmatically

Drupal 6 $reservation = new StdClass(); $reservation-&gt;type = 'reservation'; $reservation-&gt;field_reservation_tickets[0]['value'] = $form_state['values']['anzahl_tickets']; $reservation-&gt;field_reservation_email[0]['value'] = $form_state['values']['email']; $reservation-&gt;field_reservation_telefon[0]['value'] = $form_state['values']['telefon']; $reservation-&gt;field_reservation_veranstaltung[0]['nid'] = $form_state['values']['veranstaltung_nid']; $reservation-&gt;field_reservation_vorname[0]['value'] = $form_state['values']['vorname']; $reservation-&gt;title = $form_state['values']['name']; $reservation-&gt;taxonomy = array($form_state['values']['tickettyp'], array_shift(taxonomy_node_get_terms_by_vocabulary($veranstaltung, 1))); node_save($reservation); http://drupal.org/node/408540 http://current.workingdirectory.net/posts/2009/attach-file-to-node-drupa... Drupal 5 $reservation = new StdClass(); $reservation-&gt;type = 'reservation'; $reservation-&gt;field_reservation_tickets[0]['value'] = $form_state['values']['anzahl_tickets']; $reservation-&gt;field_reservation_email[0]['value'] = $form_state['values']['email']; $reservation-&gt;field_reservation_telefon[0]['value'] = $form_state['values']['telefon']; $reservation-&gt;field_reservation_veranstaltung[0]['nid'] = $form_state['values']['veranstaltung_nid']; $reservation-&gt;field_reservation_vorname[0]['value'] = $form_state['values']['vorname']; $reservation-&gt;title = $form_state['values']['name']; $reservation-&gt;taxonomy = array($form_state['values']['tickettyp'], array_shift(taxonomy_node_get_terms_by_vocabulary($veranstaltung, 1))); node_submit($reservation); // This step is needed only in Drupal 5, not in Drupal 6. node_save($reservation);

Basic Drupal 6 Form

function woof_form($title, $body) { $form['wooftitle'] = array( '#type'=&gt; 'textfield', '#title' =&gt; t('Woof'), '#default_value' =&gt; $title, '#required' =&gt; TRUE, ); $form['woofbody'] = array( '#type'=&gt; 'textarea', '#rows' =&gt; '20', '#title' =&gt; t('Woof'), '#default_value' =&gt; $body, '#required' =&gt; TRUE, ); $form['submit'] = array( '#type'=&gt; 'submit', '#title' =&gt; t('Speichern'), '#default_value' =&gt; 'Speichern', '#required' =&gt; TRUE, ); return $form; }

Form alter

function fflyr_form_alter(&amp;$form, $form_state, $form_id) { if ($form_id == 'flyer_node_form') { unset($form['buttons']['preview']); unset($form['body_field']['format']); unset($form['body_field']['teaser_include']); } } taxonomy_node_get_terms_by_vocabulary(); taxonomy_node_get_terms();

render a block

$block = module_invoke('block', 'block', 'view', $block_id); print $block['content'];

Handling ISO date with MySQL

$where[] = " DATE_FORMAT(STR_TO_DATE(field_date_value , '%%Y-%%m-%%dT%%H:%%i:%%s'), '%%Y-%%m-%%d') = '".date('Y-m-d')."' ";

Populate CCK Node Reference Field and hide it

Drupal 6 function yourmodule_form_alter(&amp;$form, $form_state, $form_id) { $form['#after_build'][] = 'yourmodule_after_build'; } function yourmodule_after_build($form, &amp;$form_state) { switch ($form['form_id']['#value']) { case 'your_form': $form['field_event_portal_nid']['nid']['nid']['#value'] = (int) arg(3); $form['field_event_portal_nid']['#access'] = false; break; } return $form; } Drupal 6 user_is_logged_in(); useful in hook_menu $items['dashboard/overview'] = array( 'title' =&gt; t('My Dashboard'), 'page callback' =&gt; 'page_dashboard', 'access callback' =&gt; 'user_is_logged_in', ); CCK Checkbox PHP Code with correct Label display return array(0=&gt;'Image as Popup', 1=&gt;'Image as Popup'); Date Field for a form Drupal 6 $date = '2008-12-31'; // Provide a default date in the format YYYY-MM-DD HH:MM:SS. // Provide a format using regular PHP format parts (see documentation on php.net). // If you're using a date_select, the format will control the order of the date parts in the selector, // rearrange them any way you like. Parts left out of the format will not be displayed to the user. $format = 'm/d/Y'; $form['my_date_field'] = array( '#type' =&gt; 'date_text', // types 'date_popup', 'date_select', 'date_text' and 'date_timezone' are supported. See .inc file. '#title' =&gt; t('Select a date'), '#default_value' =&gt; $date, '#date_format' =&gt; $format, '#date_label_position' =&gt; 'within', // 'above', 'within' or 'none', default is 'above' '#date_timezone' =&gt; 'America/Los Angeles', // Optional, if your date has a timezone other than the site timezone. '#date_increment' =&gt; 15, // Optional, used by the date_select and date_popup elements to increment minutes and seconds. '#date_year_range' =&gt; '-3:+3' // Optional, used to set the year range (back 3 years and forward 3 years is the default). ); http://drupal.org/node/290758 Avoid wrong count query on theme_pager. remove newlines and whitespaces before using pager_query $sql = str_replace(array("\n", "\r", "\t"), ' ', $sql); $result = pager_query($sql); Preserve Menu context $item = menu_get_item(); if ($item) { $item['href'] = 'job-vacancies'; //Menueintrag (Pfad) unter dem der Node angezeigt werden soll menu_set_item(NULL, $item); } pragmatically change user form function custom_theme(){ $register['user_profile_form'] = array( 'arguments' =&gt; array('form' =&gt; NULL), //'template' =&gt; 'user-profile-form', ); return $register; } function custom_user_profile_form($form) { $output = theme_part(t('Benutzer erfassen/bearbeiten'), drupal_render($form)); return $output; } how to change nodereference options title or value or whatever function custompresseberichte_form_alter(&amp;$form, $form_state, $form_id) { if ($form_id == 'pressebericht_node_form') { $form['field_pb_standorte_rel']['#pre_render'] = array('custompresseberichte_form_pre_render'); $form['field_pb_standorte_rel']['#post_render'] = array('custompresseberichte_form_post_render'); } } function custompresseberichte_form_pre_render($form) { if (is_array($form['nid']['nid'])) { foreach($form['nid']['nid'] as $key =&gt; $value) { if (is_numeric($key)) { $node = node_load($key); $form['nid']['nid'][$key]['#title'] = $node-&gt;title .' - '.$node-&gt;field_standort_bezeichnung[0]['value']; } } } return $form; } function custompresseberichte_form_post_render($content, $element) { return $content; } http://drupal.org/node/339730 Enable attachments (upload module) in your custom form. function MY_MODULE_my_form_node_form($form_state, $node) { //important that your $form_id ends with 'node_form' $form = array(); //add node values to the form $form['#node'] = $node; $form['type'] = array('#value'=&gt;'MY_MODULE_my_form'); $form['my_textfield'] = array( '#type' =&gt; 'textfield', '#title' =&gt; t('textfield'), '#default_value' =&gt; $node-&gt;field_my_textfield[0]['value'], ); $form['#submit'][] = 'upload_node_form_submit'; $form['#submit'][] = 'MY_MODULE_my_form_node_form_submit'; return $form; } function MY_MODULE_my_form_node_form_submit($form, &amp;$form_state) { $nid = (int) $form_state['values']['nid']; $node = node_load($nid, NULL, true); $node-&gt;field_my_textfield[0]['value'] = $form_state['values']['my_textfield']; //add files to the node if (is_array($form_state['values']['files'])) { foreach($form_state['values']['files'] as $fid =&gt; $file) { $node-&gt;files[$fid] = $file; } } node_save($node); } Include required files require_once('./'. drupal_get_path('module', 'custommodule') ."/myinclude.inc.php"); Add captcha programmatically to any Drupal form $form['my_captcha_element'] = array( '#type' =&gt; 'captcha', '#captcha_type' =&gt; 'captcha/Math', //'#captcha_type' =&gt; 'image_captcha/Image', '#suffix' =&gt; '' );

Imagecache: save preset and actions pragmatically

$new_preset = array( 'presetid' =&gt; '', 'presetname' =&gt; 'user_pic_xs' ); $preset = imagecache_preset_save($new_preset); $action = array( 'presetid' =&gt; $preset['presetid'], 'actionid' =&gt; '', 'action' =&gt; 'imagecache_scale', 'data' =&gt; array( 'width' =&gt; 100, 'height' =&gt; '', 'upscale' =&gt; 0 ) ); imagecache_action_save($action); $action = array ( 'presetid' =&gt; $preset['presetid'], 'actionid' =&gt; '', 'action' =&gt; 'imagecache_crop', 'data' =&gt; array ( 'width' =&gt; 32, 'height' =&gt; 32, 'xoffset' =&gt; 'center', 'yoffset' =&gt; 'center' ) ); imagecache_action_save($action);

Neuen Kommentar schreiben

Plain text

  • Keine HTML-Tags erlaubt.
  • Internet- und E-Mail-Adressen werden automatisch umgewandelt.
  • HTML - Zeilenumbrüche und Absätze werden automatisch erzeugt.
Image CAPTCHA
Enter the characters shown in the image.