Skip to content

Instantly share code, notes, and snippets.

@keeprock
Last active September 11, 2015 13:58
Show Gist options
  • Save keeprock/696f2a6397c73a085ee5 to your computer and use it in GitHub Desktop.
Save keeprock/696f2a6397c73a085ee5 to your computer and use it in GitHub Desktop.
Loads views with ajax. - Generating links with special addresses - Creating menu item with ajax page callback - Writing ajax callback with Drupal Ajax functions - Loading view with contextual filters (from url) - Replace view with Drupal Ajax functions
function custom_menu() {
$items = array();
$items['ajax/custom_module/custom_action/%/%'] = array(
'title' => 'Title',
'delivery callback' => 'ajax_deliver', // important here!
'page callback' => 'custom_module__pagecallback',
'page arguments' => array(3,4), // index starts with zero
'type' => MENU_CALLBACK,
'access callback' => TRUE
);
return $items;
}
function custom_module__pagecallback($argument_from_url, $js_status) {
drupal_add_js(drupal_get_path('module', 'a2') . '/a2_proto.js');
$path = 'relative_url_of_the_view/' . $SOME_ID_FROM_ARGS;
if ($js_status == 'nojs') {
drupal_goto($path);
}
$commands = array();
$view = views_get_view('NAME_OF_THE_VIEW');
$view->set_display('page');
$view->set_arguments(array($argument_from_url));
$view->pre_execute();
$view->execute();
$result = $view->render();
$commands[] = ajax_command_html('JQUERY_SELECTOR_TO_TARGET', $result);
$active_id = '.WRAPPER a.active';
$new_id = '.WRAPPER a.object-' . $SOME_ID_FROM_ARGS;
$commands[] = ajax_command_invoke($active_id, 'removeClass', array('active'));
$commands[] = ajax_command_invoke($new_id, 'addClass', array('active'));
if ($alias = drupal_lookup_path('alias', $path)) {
$url = $alias;
} else {
$url = $path;
}
$commands[] = array(
'command' => 'ta_history',
'url' => '/' . $url
);
return array('#type' => 'ajax', '#commands' => $commands);
}
(function($) {
Drupal.ajax.prototype.commands.custom_history = function(ajax, response, status) {
history.pushState(null, null, response.url);
}
}(jQuery));

Settings in Views

Adding contextual filter

  • Create new contextual filter with "Default value is provided".
  • Turn on "Use AJAX"
<a href="ajax/path/args/nojs" class="use-ajax object-[id]"></a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment