9
Drupal Sins How I learned to stop thinking and love sites that bomb. By: Aaron Crosman

Sins Against Drupal 1

Embed Size (px)

Citation preview

Page 1: Sins Against Drupal 1

Drupal Sins

How I learned to stop thinking and love sites

that bomb.

By: Aaron Crosman

Page 2: Sins Against Drupal 1

The Goal

Allow an existing JavaScript app to get an

arbitrary node as JSON through an AJAX

callback.

Page 3: Sins Against Drupal 1

The sinful solution

Create a custom response handler within

template.php that executes every time

template.php is loaded.

Page 4: Sins Against Drupal 1
Page 5: Sins Against Drupal 1

Better Solutions

All:

Views with a JSON display

Drupal 7:

https://www.drupal.org/project/contentasjson

Drupal 6:

Custom handler in template.php done right.

Page 6: Sins Against Drupal 1

https://www.drupal.org/node/174008template.php

<?php

function _phptemplate_variables($hook, $vars) {

switch ($hook) {

case 'page':

// If the page was requested with the jQuery ajax functionalities, an HTTP header (X-Requested-

With: XMLHttpRequest)

// will be sent to the server, making it possible to identify if we should serve the content as

JSON

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XmlHttpRequest' ==

$_SERVER['HTTP_X_REQUESTED_WITH']) {

// Now that we know that the page was requested via remote scripting (AJAX) we can serve the

content as JSON

// by telling Drupal to use a different template for the page (in this case page-json.tpl.php)

$vars['template_files'] = is_array($vars['template_files']) ? $vars['template_files'] : array();

$vars['template_files'][] = 'page-json';

}

break;

}

}

?>

page-json.tpl.php

<?php

if($messages) {

$content = $messages.$content;

}

echo drupal_to_js($content);

?>

Page 7: Sins Against Drupal 1

Just do it in views

https://www.drupal.org/project/views_datasource

Drupal 6 and 7, gives you a couple display

styles, including JSON.

You can output things any way views allows

not just dumping a node to JSON.

Page 8: Sins Against Drupal 1

Create your view

Page 9: Sins Against Drupal 1

Pick your fields and set the filter