get Dataobjects from Children - SilverStripe 3.1

回眸只為那壹抹淺笑 提交于 2019-12-11 19:39:36

问题


I've got a GalleryHolder with Gallery-Pages as children. Each Gallery-Page has a Dataobject(VisualObject) to store the images.

I managed it to get 3 random images from a GalleryPage on it's gallery page and 3 random images from all galleries on the GalleryHolder page.

But what I want are 3 random images for each gallery shown on the GalleryHolder page.

Here's my Code, can someone tell me how to do that?

  • GalleryHolder: http://sspaste.com/paste/show/525e4b9134940
  • Gallery: http://sspaste.com/paste/show/525e4bb25f236
  • VisualObject: http://sspaste.com/paste/show/525e4bd3cdfff

回答1:


the simple solution is to just foreach your children

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;
}

// EDIT as reponse to your comments:

if you want it to be grouped by gallery, I would do it different all together (forget the above code and just do the following):

put this in your Gallery class:

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

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

and then in template of the Parent (the GalleryHolder) you just call that function:

// 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 another comment asks for an exaple of a single dataobject:

if you just want 1 random gallery image, use the following:

// 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();
    }
}

and then in template you access the method directly:
$RandomObject.ID or $RandomObject.Visual or any other property
or you can use <% with %> to scope it:

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


来源:https://stackoverflow.com/questions/19398514/get-dataobjects-from-children-silverstripe-3-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!