Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Customising the CMS /

Show CMS fields based on page access (CanViewType)


Reply


4 Posts   1176 Views

Avatar
NickJacobs

Community Member, 144 Posts

1 March 2011 at 3:49pm

Edited: 01/03/2011 3:49pm

Hi, in project we have an issue where it is not immediately obvious if a page is viewable only by logged in users (without going into the Access tab) and this is causing problems for the client. I want to be able to add a literal field on the main tab, saying something like "this page is not publicly viewable..etc etc'. I want to do something like:

if(($this->CanViewType == 'OnlyTheseUsers') || ($this->CanViewType == 'LoggedInUsers')) {   
$f->addFieldToTab( 'Root.Content.Main', new LiteralField('info1','This page is restricted (not publicly viewable) - change this behaviour on the Access tab'),'Title');
}

This works kinda ok, but since most pages underneath a secure section have a CanViewType = inherit it fails on those pages....
Are there any magic methods, or easier way to do this?

Avatar
Willr

Forum Moderator, 5513 Posts

1 March 2011 at 5:31pm

Using the built in canView() method would be the away to go but it's not quite what you want in this case as you don't have a member record to test it against but you could create a fake one.

$member = new Member();

if(!$this->canView($member)) {
// show msg
}

Avatar
NickJacobs

Community Member, 144 Posts

2 March 2011 at 12:15pm

Edited: 02/03/2011 12:16pm

Hi Will,

$member = new Member();

if(!$this->canView($member)) {
$f->addFieldToTab( 'Root.Content.Main', new LiteralField('info1','<p id=securepage><span>This page is restricted (not publicly viewable) - you can change this behaviour if required on the Access tab</span></p>'),'Title');
}

this doesn't work for what I want to do...just re-reading my post maybe I wasn't quite clear. I want this to show up in the CMS on the Main tab. Wouldn't the fact that I am already logged in as admin override this?...sorry I don't know enough about how Member works

Avatar
Willr

Forum Moderator, 5513 Posts

2 March 2011 at 9:42pm

Wouldn't the fact that I am already logged in as admin override this?

Thats how canView() works by default, but like that example I'm passing in a blank $member record. Since that member record isn't logged in at all it should replicate a non logged in user. You can see the code which powers canView - https://github.com/silverstripe/sapphire/blob/2.4/core/model/SiteTree.php#L768. Not sure why a blank member wouldn't work from looking at that code.