在CMS中查看草稿预览模式时使用SilverStripe 3我收到以下错误:
[用户错误]未捕获异常:对象 - > __ call():'PortfolioPage'上不存在'featuredimage'方法
这仅在草稿模式下发生,而不是在发布模式下发生。我很困惑为什么。 它在前端很好并且做了它应该做的但是在草稿中抛出错误。
PortfolioPage.ss
<div class="content-container unit size3of4 lastUnit">
<article>
<div class="content">
$Content
<div id="container">
<% loop $DescendantFeaturedImages %>
<% if $FeaturedImage %>
<div class="item $Parent.URLSegment">
<a href="$Link" title="$Parent.Title - $Title">
<img src="$FeaturedImage.URL" width="100%" />
<div id="mask">
<span class="TitleContainer">
<h4>$Parent.Title</h4>
<p>$Title</p>
</span>
</div>
</a>
</div>
<% end_if %>
<% end_loop %>
<div>
</div>
</article>
$Form
$PageComments
</div>
PortfolioPage.php
class PortfolioPage extends Page {
}
class PortfolioPage_Controller extends Page_Controller {
public function init() {
parent::init();
Requirements::css( 'gallery/css/gallerystyles.css' );
}
function DescendantFeaturedImages() {
$featuredImages = array();
foreach ( $this->Children() as $child ) {
foreach ( $child->Children() as $grandChild ) {
$image = $grandChild->FeaturedImage();
if ( $image ) {
array_push( $featuredImages, $grandChild );
}
}
}
shuffle( $featuredImages );
return ArrayList::create( $featuredImages );
}
}
答案 0 :(得分:2)
@ 3dgoo就绪,因为$grandChild
没有名为FeaturedImage
的函数而引发错误。如果未在页面类型的祖先中的任何类上定义(作为您自己在has_one
关系生成的函数上的函数),则会抛出该错误。查看调用堆栈,您可以看到它是PortfolioPage
的{{1}}对象。
仅在草稿上发生这种情况的一个原因是草稿网站上的网站树与发布的树不同。
要避免此特定网页类型出现此错误,您需要在$grandChild
课程中定义名为has_one
的函数(或FeaturedImage
关系)。
要避免在所有页面类型上出现此错误,您可以执行以下任一操作:
PortfolioPage
功能是否存在FeaturedImage
函数
醇>
要检查函数是否存在,最好使用内置的hasMethod
函数。此函数不仅检查手动定义的方法,还可以正确处理通过FeaturedImage
添加的方法。
您的代码看起来更接近于此:
DataExtension
大多数情况下,您要编写的页面类型和来自各个模块的页面类型将继承自function DescendantFeaturedImages() {
$featuredImages = array();
foreach ( $this->Children() as $child ) {
foreach ( $child->Children() as $grandChild ) {
if ($grandChild->hasMethod('FeaturedImage')) {
$image = $grandChild->FeaturedImage();
if ( $image ) {
array_push( $featuredImages, $grandChild );
}
}
}
}
shuffle( $featuredImages );
return ArrayList::create( $featuredImages );
}
类。
假设您希望Page
直接成为FeaturedImage
图片,就是这样:
has_one
如果您的class Page extends SiteTree {
// ... any other statics you defined here ...
private static $has_one = array(
'FeaturedImage' => 'Image'
);
// ... any other functions or bits of code below here ...
}
打算成为其他人使用的模块,您不希望让他们手动在自己的PortfolioPage
类中定义它,您可能希望使用DataExtension
Page
然后只需在YML文件中添加扩展名即可添加扩展程序:
class PageExtension extends DataExtension {
// ... any other statics you defined here ...
private static $has_one = array(
'FeaturedImage' => 'Image'
);
// ... any other functions or bits of code below here ...
}