Custom Views argument Validator: views_plugin_argument_validate

views_plugin_argument_validate
Views' argument is a very useful filter,
With the same views display, but different content types, or authors, or post date etc difference situations can shine the power of arguments
And with the ability to validate an argument with some criteria,
like the node should be a specific content type

This time, the requirements is pass in date to arguments, example with URL "frontpage/20130320" displaying Mar 20th content
But there is a special requirement limit to prior 7 days only, dates before 7 days will show 403 (individual node access is not restricted)
so I write a custom argument validator:

<?php
//example.module let views knows this module implement some views api:
function example_views_api() {
  return array(
   
'api' => 3.0,
   
'path' => drupal_get_path('module', 'example') . '/includes',
  );
}
?>

<?php
//includes/example.views.inc
//MODULENAME.views.inc defines this is a custom argument validator
function exmaple_views_plugins() {
  return array(
   
'argument validator' => array(
     
'days_limit' => array(
       
'title' => t('7 days limit'),
       
'handler' => 'example_plugin_argument_validate_7_days_limit',
       
'path' => drupal_get_path('module', 'example') . '/includes',
      ),
    ),
  );
}
?>

handler exists inside its own file, so need to define the file in example.info:

files[] = includes/example_plugin_argument_validate_7_days_limit.inc

Implementation:

<?php
//example_plugin_argument_validate_7_days_limit.inc
class example_plugin_argument_validate_7_days_limit extends views_plugin_argument_validate {

  function
construct() {
   
parent::construct();
  }

  function
validate_argument($argument) {
    global
$user;

    if (
in_array('administrator', $user->roles)) {
      return
TRUE;
    }

    if(
is_numeric($argument)) {
     
// as the argument is in form of CCYYMMDD, validate it should be no more than 7 days ago
     
$date = strtotime($argument);
     
$days_ago = strtotime("-7 day");
      if(
$days_ago < $date) {
        return
TRUE;
      }
    }
    return
FALSE;
  }
}
?>
AttachmentSize
Image icon views_plugin_argument_validate.png19.16 KB
Google