6

This question is about the URL Update feature when changing the value of a Page Title field. The behaviour is coded into CMSMain.EditForm.js.

enter image description here

I'm stripping down and customising the CMS to be usable by an absolute basic computer user or the negligent client, who will most likely skip pressing the Update URL button upon page name change. In these cases it would be very convenient if the URLSegment would be automatically updated.

Q: What would be the simplest way to automatically have the URL segment updated, IE simulate the result that would appear upon clicking the "Update URL" button, after changing the Title field?

Semicolon
  • 1,904
  • 14
  • 26

1 Answers1

7

You could make an extension for SiteTree and include the function onBeforeWrite like this. This will make a change if they updated the Title and not the URL:

class AutoURLSync extends Extension {
    public function onBeforeWrite() {
        // If Title is changed, but URLSegment is not, 
        // then update the URLSegment here
        if($this->owner->isChanged('Title',2) && !$this->owner->isChanged('URLSegment',2)) {
            $this->owner->URLSegment = $this->owner->generateURLSegment($this->owner->Title);
        }
    }
}

Removing the "if" would mean it always is changed.

Add this in _config/config.yml to link up the extension:

SiteTree:
    extensions:
      - AutoURLSync
Sygmoral
  • 7,021
  • 2
  • 23
  • 31
Barry
  • 3,303
  • 7
  • 23
  • 42
  • I changed the class name (`SiteTreeExtension` seems to already exist in core files), placed the if statement in brackets (also tried removing the if statement). I get an internal error on **Publish** – Semicolon Jul 19 '16 at 14:15
  • Whats the error? is there still an error if you remove the "if"? – Barry Jul 19 '16 at 14:17
  • `Call to undefined method Extension::onBeforeWrite()` using a unique classname and removing the if statement (leaving inner part of the if statement untouched). – Semicolon Jul 19 '16 at 15:01
  • How about if it is "DataExtension" instead of "Extension" ? – Barry Jul 19 '16 at 15:05
  • Now I'm getting `Call to undefined method AutoURLSync::generateURLSegment()`. AutoURLSync is the classname I used instead of SiteTreeExtension. I think it should be `Extension` after all. I took a look in cms/code/model/SiteTreeExtension.php and couldnt find the `onBeforeWrite` function in there – Semicolon Jul 19 '16 at 15:07
  • face-palm - extensions use $this->owner-> instead of $this-> hopefully that will resolve it – Barry Jul 19 '16 at 15:11
  • I applied that, but the issue internal error was still showing. Removed `parent::onBeforeWrite();` and it works like a charm now. Cheers! – Semicolon Jul 19 '16 at 15:18
  • excellent :) now how did I leave that in there? I must test these more before posting... – Barry Jul 19 '16 at 15:20