/
SiteTreeLink.php
118 lines (96 loc) · 2.81 KB
/
SiteTreeLink.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php declare(strict_types=1);
namespace SilverStripe\LinkField\Models;
use SilverStripe\CMS\Forms\AnchorSelectorField;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\TreeDropdownField;
/**
* A link to a Page in the CMS
*
* @property int $PageID
* @property string $Anchor
* @method SiteTree Page()
*/
class SiteTreeLink extends Link
{
private static $table_name = 'LinkField_SiteTreeLink';
private static $db = [
'Anchor' => 'Varchar'
];
private static $has_one = [
'Page' => SiteTree::class
];
public function generateLinkDescription(array $data): string
{
if (empty($data['PageID'])) {
return '';
}
/** @var SiteTree $page */
$page = SiteTree::get()->byID($data['PageID']);
return $page ? $page->URLSegment : '';
}
public function getCMSFields(): FieldList
{
$this->beforeUpdateCMSFields(static function (FieldList $fields) {
// Remove scaffolded fields to we don't have field name conflicts which would prevent field customisation
$fields->removeByName([
'PageID',
'Anchor',
]);
$fields->insertAfter(
'Title',
TreeDropdownField::create(
'PageID',
'Page',
SiteTree::class,
'ID',
'TreeTitle'
)
);
$fields->insertAfter(
'PageID',
AnchorSelectorField::create('Anchor')
);
});
return parent::getCMSFields();
}
public function getURL(): ?string
{
$page = $this->Page();
$url = $page->exists() ? $page->Link() : '';
if ($this->Anchor) {
$url .= '#' . $this->Anchor;
}
return $url;
}
public function onBeforeWrite(): void
{
parent::onBeforeWrite();
$this->populateTitle();
}
protected function populateTitle(): void
{
$title = $this->getTitleFromPage();
$this->extend('updateGetTitleFromPage', $title);
$this->Title = $title;
}
/**
* Try to populate link title from page title in case we don't have a title yet
*
* @return string|null
*/
protected function getTitleFromPage(): ?string
{
if ($this->Title) {
// If we already have a title, we can just bail out without any changes
return $this->Title;
}
$page = $this->Page();
if (!$page->exists()) {
// We don't have a page to fall back to
return null;
}
// Use page title as a default value in case CMS user didn't provide the title
return $page->Title;
}
}