user3599221
user3599221

Reputation: 39

Only show todays news - Silverstripe

Hello Silverstripe Specialists!

I made the tutorial "extending a basic site" (http://doc.silverstripe.org/en/tutorials/extending_a_basic_site)

That all worked very well so far.

I made this to show the latest news on the HomePage: In HomePage.php:

// ...
public function LatestNews($num=5) {
    $holder = ArticleHolder::get()->First();
    return ($holder) ? ArticlePage::get()->filter('ParentID', 
        $holder->ID)->sort('Date DESC')->limit($num) : false;
}

And this in HomePage.ss:

// ...
public function LatestNews($num=5) {
    $holder = ArticleHolder::get()->First();
    return ($holder) ? ArticlePage::get()->filter('ParentID', 
        $holder->ID)->sort('Date DESC')->limit($num) : false;
}

That works very well!

Now my Question: All my News have a Date-Field. Is it possible to show only the News of the current Date on the HomePage?

I tried this, but this wont work (Server Error) (Datum is my Date of the News):

public function LatestNews($num) {
    $holder = ArticleHolder::get()->First();
    return ($holder) ? ArticlePage::get()->filter('ParentID', "datum == CURDATE()", 
        $holder->ID)->sort('Date DESC')->limit($num) : false;
}

Thank you very much for your help!

Upvotes: 0

Views: 742

Answers (1)

wmk
wmk

Reputation: 4626

filter() needs either two values (column and value) or an array of key-value pairs of what to filter. So if you want to filter for more than one thing you need an array as parameter:

$today = date('Y-m-d');
$todaysNews = ArticlePage::get()->filter(array(
    'ParentID' => $holder->ID, 
    'datum' => $today
));

This will return a DataList you can sort and limit like you did in your example.

See also in docs:

EDIT: So a method in your controller could look like:

public function getTodaysNews($num=5) {
    $holder = ArticleHolder::get()->First();
    $today = date('Y-m-d');
    return $holder
        ? ArticlePage::get()->filter(array(
            'ParentID' => $holder->ID, 
            'datum' => $today
            ))->sort('Date DESC')->limit($num)
        : false;
}

Upvotes: 2

Related Questions