php - SilverStripe unique URL (debug) -


in dataobject there user supplied field title has converted unique url slug.

desired result: duplicate url's should suffix value. saving 2 records title foo should result in 1 record foo value column url , second record should have value foo-2 same column.

public function onbeforewrite() {     parent::onbeforewrite();      // sanitize title field use url     $filter = urlsegmentfilter::create();     $this->url = $filter->filter($this->title);      // if url not unique, add suffix     $i = 1;     while($this->uniqueurl($this->url)) {         $i++;         $this->url = $this->url . "-" . $i;     }    } 

method: uniqueurl (within same class)

public function uniqueurl($url) {      // check if there record same url     $existingurl = dataobject::get('newsarticle', "url = '$url'");     if ($existingurl) {         // duplicate url         return false;     } else {         // unique url         return true;     } } 

saving foo twice result in foo , foo-2.

when saving 2 records same title foo results in 2 url fields foo

why have 2 foo urls?

if check db before inserting records, means check not work on record batch.

don't use loop count unique urls

you don't need loop , check every time , increment count ($i). performance wise youre far better off doing count() in query , use value next insert.

// following same 1 query. no loop needed. $count = db::query("select count(*) table title '{$filteredtitle}'")->value(); if ($count > 1) {     $filteredtitle .= "-" .  $count; } $this->url = $filteredtitle 

solutions

to onbeforewrite() possibility query data , check records before saved.

or simpler solution same results can change url in onafterwrite() , , check use amount of same titles number.

public function onafterwrite() {     parent::onafterwrite();      // sanitize title field use url     $filter = urlsegmentfilter::create();     $filteredtitle= $filter->filter($this->title);      $count = db::query("select count(*) table title '{$filteredtitle}'")->value();     if ($count > 1) {         $filteredtitle .= "-" .  $count;     }     $this->url = $filteredtitle } 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -