2013-10-16 49 views
0

我有一个GalleryHolder和Gallery-Pages作为儿童。每个图库页面都有一个DataObject(VisualObject)来存储图像。从儿童获得Dataobjects - SilverStripe 3.1

我管理它从GalleryPage上的3张随机图像和GalleryHolder页面上所有图库中的3张随机图像。

但我想要的是GalleryHolder页面上显示的每个画廊的3个随机图像。

这是我的代码, 有人可以告诉我该怎么做吗?

回答

3

简单的解决方法就是你的foreach孩子

public function getRandomPreviewForAllChildren($numPerGallery=3) { 
    $images = ArrayList::create(); 
    foreach($this->data()->Children() as $gallery) { 
     $imagesForGallery = $gallery->GalleryImages() 
      ->filter(array('Visibility' => 'true')) 
      ->sort('RAND()') 
      ->limit($numPerGallery); 
     $images->merge($imagesForGallery); 
    } 
    return $images; 
} 

//编辑为向效应初探您的意见:

,如果你想让它通过画廊进行分组,我会做不同的一起(忘了上面的代码,只是做了如下):

把这个在您的画廊类:

// File: Gallery.php 
class Gallery extends Page { 
    ... 

    public function getRandomPreview($num=3) { 
     return $this->GalleryImages() 
      ->filter(array('Visibility' => 'true')) 
      ->sort('RAND()') 
      ->limit($num); 
    } 
} 

然后在家长的模板(在GalleryHolder)你只是调用该函数:

// File: GalleryHolder.ss 
<% loop $Children %> 
    <h4>$Title</h4> 
    <ul class="random-images-in-this-gallery"> 
     <% loop $RandomPreview %> 
      <li>$Visual</li> 
     <% end_loop %> 
    </ul> 
<% end_loop %> 

// EDIT其它C omment要求提供一个单一的数据对象的的exaple:

如果你只想1幅随机库图像,使用以下命令:

// File: Gallery.php 
class Gallery extends Page { 
    ... 

    public function getRandomObject() { 
     return $this->GalleryImages() 
      ->filter(array('Visibility' => 'true')) 
      ->sort('RAND()') 
      ->first(); 
     // or if you want it globaly, not related to this gallery, you would use: 
     // return VisualObject::get()->sort('RAND()')->first(); 
    } 
} 

,然后在模板中,您直接访问的方法:
$RandomObject.ID$RandomObject.Visual或者其他财产的
或者您可以使用<% with %>到它的范围:

<% with $RandomObject %> 
    $ID<br> 
    $Visual 
<% end_with %> 
+0

嗨THX,这个做的工作。但知道我有另一个问题。我怎样才能得到每个画廊的名字? – invictus

+0

你想每个图像上的画廊的标题,或者你想按照画廊分组他们有一个标题? – Zauberfisch

+0

我想要主画廊的标题。所以图库1显示3个随机图像和图库标题,图库2显示3随机图像和图库标题等 – invictus