What would be the simplest way to automatically have the URL segment updated?
Asked Answered
C

1

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?

Colossal answered 19/7, 2016 at 12:52 Comment(0)
L
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
Lanell answered 19/7, 2016 at 13:10 Comment(8)
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 PublishColossal
Whats the error? is there still an error if you remove the "if"?Lanell
Call to undefined method Extension::onBeforeWrite() using a unique classname and removing the if statement (leaving inner part of the if statement untouched).Colossal
How about if it is "DataExtension" instead of "Extension" ?Lanell
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 thereColossal
face-palm - extensions use $this->owner-> instead of $this-> hopefully that will resolve itLanell
I applied that, but the issue internal error was still showing. Removed parent::onBeforeWrite(); and it works like a charm now. Cheers!Colossal
excellent :) now how did I leave that in there? I must test these more before posting...Lanell

© 2022 - 2024 — McMap. All rights reserved.