Tuesday, June 3, 2014

Drupal and Ajax, now with language negotiation...

Sometimes I just want to kick myself! I was struggling to set the language for a module that gets called via Ajax and that prints out the contents of a view (with supposedly the correct field language set) but the field language always went for default language...

Well, turns out, sometimes it's Just Not That Hard.

Set up the language negotiation to use prefixes and then just prefix the url with the desired language like /lang/arg

Menu hook from the module:

function example_menu(){
$items = array();
$items['example/ajaxview'] = array(
        'title' => 'Ajax View Loader',
        'page callback' => 'example_loadview',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
);
$items['sv/example/ajaxview'] = array(
        'title' => 'Ajax View Loader',
        'page callback' => 'example_loadview',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
);
$items['en/example/ajaxview'] = array(
        'title' => 'Ajax View Loader',
        'page callback' => 'example_loadview',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
);
$items['de/example/ajaxview'] = array(
        'title' => 'Ajax View Loader',
        'page callback' => 'example_loadview',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
);
return $items;
}

The callback:

function example_loadview($arg){
  // Print the output from a view that takes a contextual argument
  print views_embed_view('myajaxview', 'my_display_id, $arg);
  exit;
}


Calling the function from javascript (Drupal keeps a note of the path prefix used in Drupal.settings.pathPrefix)

var url = "/" + Drupal.settings.pathPrefix + "example/ajaxview/" + arg;
$.get(url, function (data) {
  alert(data); // Or do something with it
});

The language negotiation will do the rest of the heavy lifting.

No comments:

Post a Comment