pinkp
pinkp

Reputation: 455

SilverStripe 3 Filtering / Filtering Out DataObjects in a Function

I've found some examples of filtering but nothing clear enough to answer my question. I have the following function to get my grand children pages. I'm trying to count them but only if they meet certain criteria. In my case if they do not have X,Y,Z then include them in the count.

In other words would like to add a list / array of arguments to the function that if ANY are true then don't include them and filter them out. For example if DealerOnly = true ignore.

I thought about doing this in the template and using if / else but the count won't display like this so I haven't gone down that route.

Alternative methods welcome.

<% loop $GrandChildren %>$Count<% end_loop %>   

Possible help: http://www.silverstripe.org/community/forums/data-model-questions/show/23507

Docs here: (not quite what I need though) https://docs.silverstripe.org/en/3.1/developer_guides/model/searchfilters/

My function which returns my grandchild pages.

public function getGrandChildren() {
    $ids = Page::get()->filter(array('ParentID' => $this->ID))->getIDList();
    $grandChildren = Page::get()->filter(array(
        'ParentID' => $ids
    ));

    return $grandChildren;
}

In my template which counts all the pages

$GrandChildren.Count

Upvotes: 2

Views: 2691

Answers (3)

pinkp
pinkp

Reputation: 455

For some reason I didn't get the other answers to work. I found out you can filter in the template.

$GrandChildren.Filter('DealerOnly','0').Count

Upvotes: 2

wmk
wmk

Reputation: 4626

Well, you can manipulate your DataList like you want, e.g.

public function getGrandChildren() {
    $ids = Page::get()->filter(array('ParentID' => $this->ID))->getIDList();
    $grandChildren = Page::get()
        ->filter(array(
            'ParentID' => $ids
        ))
        ->exclude(array('DealerOnly' => true));

    return $grandChildren;
}

See API docs for DataList::exclude and docs

If you want to exclude if any of more columns in the database is true, you have to use the :not searchfilter modifier as unfortunately there is no excludeAny() function.

->filter(array('DealerOnly:not' => true))
->filter(array('Foo:not' => 'Bar'))

Upvotes: 3

Barry
Barry

Reputation: 3318

You can use ->exclude, so for you DataList...

$grandChildren->exclude(array(
  'DealerOnly' => true
));

Upvotes: 1

Related Questions