Skip to content

Commit

Permalink
NEW: Empty link title fallbacks to Page.
Browse files Browse the repository at this point in the history
  • Loading branch information
mfendeksilverstripe committed Oct 25, 2021
1 parent 95f8759 commit e22a00d
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/Models/SiteTreeLink.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public function generateLinkDescription(array $data): string
return '';
}

/** @var SiteTree $page */
$page = SiteTree::get()->byID($data['PageID']);

return $page ? $page->URLSegment : '';
Expand Down Expand Up @@ -58,12 +59,26 @@ public function getCMSFields()
return $fields;
}

public function getURL()
public function getURL(): ?string
{
$url = $this->Page ? $this->Page->Link() : '';

if ($this->Anchor) {
$url .= '#' . $this->Anchor;
}

return $url;
}

public function onBeforeWrite(): void
{
parent::onBeforeWrite();

if ($this->Title || !$this->Page->exists()) {
return;
}

// Use page title as a default value in case CMS user didn't provide the title
$this->Title = $this->Page->Title;
}
}
29 changes: 29 additions & 0 deletions tests/php/LinkModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

namespace SilverStripe\Link\Tests;

use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\Link\Models\Link;
use SilverStripe\Link\Models\SiteTreeLink;
use SilverStripe\ORM\ValidationException;

class LinkModelTest extends SapphireTest
{
Expand All @@ -18,4 +21,30 @@ public function testLinkModel(): void

$this->assertEquals('FormBuilderModal', $model->LinkTypeHandlerName());
}

/**
* @throws ValidationException
*/
public function testSiteTreeLinkTitleFallback(): void
{
/** @var SiteTreeLink $model */
$model = $this->objFromFixture(SiteTreeLink::class, 'page-link-1');

$this->assertEquals('PageLink1', $model->Title, 'We expect to get a default Link title');

/** @var SiteTree $page */
$page = $this->objFromFixture(SiteTree::class, 'page-1');

$model->PageID = $page->ID;
$model->Title = '';
$model->write();

$this->assertEquals($page->Title, $model->Title, 'We expect to get the linked Page title');

$customTitle = 'My custom title';
$model->Title = $customTitle;
$model->write();

$this->assertEquals($customTitle, $model->Title, 'We expect to get the custom title not page title');
}
}
8 changes: 8 additions & 0 deletions tests/php/LinkModelTest.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
SilverStripe\Link\Models\Link:
link-1:
Title: Link1

SilverStripe\Link\Models\SiteTreeLink:
page-link-1:
Title: PageLink1

SilverStripe\CMS\Model\SiteTree:
page-1:
Title: Page1

0 comments on commit e22a00d

Please sign in to comment.