TJR
TJR

Reputation: 6577

Drupal redirect when access denied

We use a module in our projekt named "certificate". There is one Function in the *.module file which contains this:

function certificate_menu() {
    $items['node/%node/certificate'] = array(
    'title' => 'Certificate',
    'description' => 'Display earned certificate for this node',
    'page callback' => 'certificate_node_certificate',
    'page arguments' => array(1),
    'access callback' => 'certificate_can_access_certificate',
    'access arguments' => array(1),
    'file' => 'certificate.pages.inc',
    'type' => MENU_LOCAL_TASK,
  );
}

There is a "certificate_can_access_certificate" callback to check if the User has Access to download a certificate.

Whan I now try is to make a redirect to page "/my/another/access/denied/page/for/certificate" when this callback returns false.

What is now the recommended way to solve this ?

1) Manipulate the callback function and everytime when its returned "False" I just write an exit; there and redirect before with location() ?

2) Is there a way to create a function in my own custom module to make this redirect possible ?

3) Do I have to manipulate the function certificate_menu() in a special way ?

I do not know much about Drupal so I dont know whats the best way to do and how I have to do this ...

Upvotes: 1

Views: 1391

Answers (1)

oknate
oknate

Reputation: 1148

You can use "drupal_goto" function within your access callback to redirect.

Here's an example, where if you add ?doredirect=true it will redirect from the access function.

function certificate_menu() {
    $items['mytestpage'] = array(
    'title' => 'Certificate',
    'description' => 'Display earned certificate for this node',
    'page callback' => 'certificate_testpage',
    'access callback' => 'certificate_access',
  );

  return $items;
}

function certificate_testpage() {
  return 'testing!';
}

function certificate_access() {

  if(isset($_GET['doredirect'])) {
    drupal_goto('', array(), 301);
  }
  return 1;
}

Also, please note, you need to return $items within your hook_menu, otherwise your page callback won't register.

Upvotes: 1

Related Questions