在此數據對象有一個用戶提供的字段標題必須轉換爲唯一的URL段落。SilverStripe唯一URL(調試)
預期結果:重複的網址應該爲其值添加後綴。因此,使用標題Foo
保存2條記錄應得到一條記錄,其foo
值爲列URL
,第二條記錄的值應爲同一列的值foo-2
。
public function onBeforeWrite() {
parent::onBeforeWrite();
// Sanitize Title field to use for URL
$filter = URLSegmentFilter::create();
$this->URL = $filter->filter($this->Title);
// If URL is not unique, add suffix
$i = 1;
while($this->uniqueURL($this->URL)) {
$i++;
$this->URL = $this->URL . "-" . $i;
}
}
方法:uniqueURL(同一類內)
public function uniqueURL($URL) {
// Check if there is a record with the same URL
$existingURL = DataObject::get('NewsArticle', "URL = '$URL'");
if ($existingURL) {
// this is a duplicate URL
return false;
} else {
// this is a unique url
return true;
}
}
保存Foo
兩次將導致foo
和foo-2
。
當保存兩個記錄具有相同名稱Foo
產生兩個URL字段與foo
你的問題是什麼,第一個案例需要'foo'和'foo-2',第二個案例呢?或在兩種情況下'foo-1'和'foo-2'? – Timmetje
'foo'爲第一,'foo-2'爲第二個 – Faloude