1
votes

I'm developing a Silverstripe module module allowing users to subscribe to a website which also sends out a monthly magazine.

There will be 2 levels of user in a single group. All users in this group will have be able to login to the site, but some content will only be visible to those with an active, paid subscription.

I have a DataExtension extending the main Page object. This allows me to have a boolean field to indicate subscriber only content. My intention was to add the "canView" function, which would perform the necessary checks on the user's subscription status to hide the links from inactive members, returning true for admin of course.

class MemberPageExtension extends DataExtension {
    static $db = array(
        'SubscribersOnly' => 'Boolean'
    );
    public function canView(){
        // perform subscription checks here
        return false ; // result will be dependent on subscription status
    }
}

Unfortunately canView() doesn't seem to be working/available on a DataExtension, so now I'm a little stuck as to how to achieve this.

Is there a way to make the "can" functions available to a DataExtension on a Page, or produce a similar effect without the need for if statements in the templates?

1

1 Answers

1
votes

Citing the official documentation:

If the Extension needs to modify an existing method it's a little trickier. It requires that the method you want to customize has provided an Extension Hook in the place where you want to modify the data.

I just checked the cms/code/model/SiteTree.php code and I found these lines:

// Standard mechanism for accepting permission changes from extensions
$extended = $this->extendedCan('canView', $member);
if($extended !== null) return $extended;

So... yes, you can modify the canView behavior, and by declaring a canView function (as you did).

Your problem is somewhere else: you must show us how canView is defined.

Addendum

A quick test: I just saved this code as mysite/code/Page.php on a bare SilverStripe installation.

<?php

class Page extends SiteTree {
}

class Page_Controller extends ContentController {
}

class MemberPageExtension extends DataExtension {

    public function canView(){
        // perform subscription checks here
        return false ; // result will be dependent on subscription status
    }
}

$instance = new Page();
Debug::show($instance->canView());

Page::add_extension('MemberPageExtension');

$instance = new Page();
Debug::show($instance->canView());

The first call returns true, the second false.

Again: your problem resides elsewhere.