Node ID as View Argument from SEO-friendly URL Path

Scenario: two content types - department, employee. Employee has a CCK node reference back to department, with a Pathauto setting for URL generation in the format of department/employee. Within the Views page views we want 2 or more separate lists, perhaps one displaying current associated employee projects, and another one all past projects. The respective page displays would have paths set to department/%/current and department/%/past, with % being the employee argument used within the view.

Normally, that's not a problem as the argument can be set to Provide default argument and the Default argument type set to Node ID from URL. Views can use multiple arguments in the URL if needed, but since the argument in this URL is followed by another string, it is technically not a valid path - only one generated by views. Therefore, when the query attempts to obtain argument from the URL, such as department/john-doe/current - it returns empty - there is no such valid URL.

The solution is to set the Action to take if argument is not present to Hide view / Page not found (404) and then use the Validator option for PHP Code. This area allows for the code to alter the argument and return it back to the query. For the above scenario, it searches for department/john-doe and gets the correct NID. This snippet effectively uses the first two parts of the URI to obtain the node ID from Drupal's internal path and sets it as the argument to be used in the query.

// Check to see if the argument is already numeric
// Useful with views Preview
if (is_numeric($argument)) {
  return TRUE;
}
// Check to see if wildcard is used
elseif ($argument == 'all') {
  return TRUE;
} else {

// Get arg(0) and arg(1) being the first two arguments 
// from the URL after domain.com and
// convert them from a URL alias to Drupal's internal path
$path = drupal_get_normal_path(arg(0) . '/' . arg(1));

// Split out the path into individual elements that are
// separated by '/'
// Possibility of further actions depending on 
// standard Drupal paths (such as 'node' or 'admin')
$path = explode('/', $path);

// Validate that returned path is valid
// and set the NID as the argument
// To validate this argument, return TRUE
if ($path[0] == 'node' && is_numeric($path[1])) {
  $handler->argument = $path[1];
  return TRUE;
}

}
// Something wasn't right
return FALSE;

This can be easily adjusted if the view display path contains the argument in the third position, or perhaps specific action is needed for certain node types.

Share this post