I've been following Silverstripe DataObjects as Pages - Part 2: Using Model Admin and URL Segments to create a product catalogue tutorial on my localhost and running into a sidebar problem.
When I use the same method to create a sidebar as tutorial one, an error message shows on my site [User Error] Uncaught Exception: Object->__call(): the method 'categorypages' does not exist on 'Product'
This is the code I added to Product.php for sidebar to appear.
//Return the Title as a menu title
public function MenuTitle()
{
return $this->Title;
}
//Ensure that the DO shows up in menu (it is needed otherwise sidebar doesn't show when not logged in)
function canView()
{
return $this->CategoryPages()->canView();
}
Does anyone know how to fix this problem? Thanks very much.
have you tried $this->Categories()->First()->canView()
?
reading the comments below it seems to me you're trying to call canView on the list of all of your related CategoryPage objects (ComponentSet)
[EDIT]
as you mentioned in the comments below, you get an error now in the cms calling canView on a non-object. my guess is you haven't attached any Categories yet to some Product, therefore Categories()->First() returns NULL. please try:
function canView() {
//always show this product for users with full administrative rights (see tab 'Security' in CMS
if(Permission::check('ADMIN')) return true;
//go and get all categories this product belongs to
$categories = $this->Categories();
//are there any categories?
if($categories->Count() > 0) {
//get the first category to see wheter it's viewable by the current user
return $categories->First()->canView();
} else {
//product doesn't belong to any categories, so don't render it
return false;
}
}
i don't really get though why you implemented this canView check. does it really matter wheter a Product is already related to a category? otherwise, just return true;
in your canView method.
I haven't tried it myself, but taking a look at the comments you should change $Category = $this->CategoryPages()->First();
to $Category = $this->Categories()->First();
The error would suggest to me that you do not have a has_one relationship on your Product class with the name 'CategoryPages'. The example in the tutorial has the following on the StaffMember class (note the StaffPage relationship):
//Relations
static $has_one = array (
'StaffPage' => 'StaffPage',
'Photo' => 'Image'
);
This is what is referenced in the example canView function ($this->StaffPage()):
function canView()
{
return $this->StaffPage()->canView();
}
Do you have an equivalent relationship named 'CategoryPages' on your Product? You need to specify the relationship to the parent correctly.