/
BlogRecentPostsWidget.php
92 lines (78 loc) · 1.88 KB
/
BlogRecentPostsWidget.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
namespace SilverStripe\Blog\Widgets;
use SilverStripe\Blog\Model\Blog;
use SilverStripe\Control\Director;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\NumericField;
use SilverStripe\ORM\DataList;
use SilverStripe\Widgets\Model\Widget;
if (!class_exists(Widget::class)) {
return;
}
/**
* @method Blog Blog()
*
* @property int $NumberOfPosts
*/
class BlogRecentPostsWidget extends Widget
{
/**
* @var string
*/
private static $title = 'Recent Posts';
/**
* @var string
*/
private static $cmsTitle = 'Recent Posts';
/**
* @var string
*/
private static $description = 'Displays a list of recent blog posts.';
/**
* @var array
*/
private static $db = [
'NumberOfPosts' => 'Int',
];
/**
* @var array
*/
private static $has_one = [
'Blog' => Blog::class,
];
/**
* @var string
*/
private static $table_name = 'BlogRecentPostsWidget';
/**
* {@inheritdoc}
*/
public function getCMSFields()
{
$this->beforeUpdateCMSFields(function ($fields) {
/**
* @var FieldList $fields
*/
$fields->merge([
DropdownField::create('BlogID', _t(__CLASS__ . '.Blog', 'Blog'), Blog::get()->map()),
NumericField::create('NumberOfPosts', _t(__CLASS__ . '.NumberOfPosts', 'Number of Posts'))
]);
});
return parent::getCMSFields();
}
/**
* @return array|DataList
*/
public function getPosts()
{
$blog = $this->Blog();
if ($blog) {
return $blog->getBlogPosts()
->filter('ID:not', Director::get_current_page()->ID)
->sort('"PublishDate" DESC')
->limit($this->NumberOfPosts);
}
return [];
}
}