13/03/2017 2:41pm

PHP | Working Example - DataObject with Link Extension


<?php

class DataObjectLinkExtension extends DataExtension {

public $show_function = 'show';

private static $db = [
'URLSegment' => 'Varchar(255)',
];

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

$owner = $this->owner;

if(!$owner->URLSegment && $owner->Title) {
$owner->URLSegment = $owner->generateURLSegment($owner->Title);
} else if($owner->isChanged('URLSegment', 2)) {
$owner->URLSegment = $owner->generateURLSegment($owner->URLSegment);
}

$count = 2;
while(!$owner->validURLSegment()) {
$owner->URLSegment = preg_replace('/-[0-9]+$/', null, $owner->URLSegment) . '-' . $count;
$count++;
}
}

public function validURLSegment() {
$owner = $this->owner;
$class = $owner->ClassName;

$existingItem = $class::get()
->filter('URLSegment', $owner->URLSegment)
->exclude('ID', $owner->ID)
->first();
return !($existingItem);
}

public function generateURLSegment($title){
$owner = $this->owner;
$filter = URLSegmentFilter::create();

$t = $filter->filter($title);
if(!$t || $t == '-' || $t == '-1') $t = $this->getShowFunction() . '-' . $owner->ID;

$owner->extend('updateURLSegment', $t, $title);

return $t;
}

public function Link() {
$owner = $this->owner;

$link = Director::get_current_page()->Link() . $this->getShowFunction() . '/' . $owner->URLSegment;

return $link;
}

public function AbsoluteLink() {
return Director::absoluteURL($this->Link());
}

public function updateCMSFields(FieldList $fields) {
$fields->insertAfter(
SiteTreeURLSegmentField::create('URLSegment', 'URL')
->setURLPrefix($this->getShowFunction() . '/')
, 'Title');
}

public function getShowFunction() {
if($name = $this->owner->show_function) {
return $name;
}

return $this->show_function;
}
}