Jump to:

5513 Posts in 1732 Topics by 1218 members

Customising the CMS

SilverStripe Forums » Customising the CMS » Auto-update image upload directory

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Page: 1
Go to End
Author Topic: 466 Views
  • alexanderhiam
    Avatar
    Community Member
    2 Posts

    Auto-update image upload directory Link to this post

    Hi all,

    I've hit a bit of a snag which I'm sure has a simple solution, but I can't for the life of me figure it out. I have a page with an image upload field, and I need the upload directory to be /[parent page->URLSegment]/[URLSegment]/. At the moment I'm doing this with UploadField->setFolderName() in getCMSFields(), but this of course only changes the upload directory when the page is saved. Ideally I want it to change as soon as the URLSegment changes, just like the URLSegment does when the Title is changed.

    -Alex

  • juergr
    Avatar
    Community Member
    17 Posts

    Re: Auto-update image upload directory Link to this post

    You should be able to do this in the 'onBeforeWrite()' functions of the different pages.

    Have a look at this code:

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

          if($this->isChanged('Title')) {
             $this->URLSegment = $this->createUniqueURLSegement();
          }

          if($this->isChanged('URLSegment')) {
             $fields = $this->getChangedFields();
             $URLSegment = $fields['URLSegment'];
             $pdfFolder = Folder::find(self::$pdf_folder . '/' . $URLSegment['before']);
             if($pdfFolder) {
                $pdfFolder->setName($URLSegment['after']);
                $pdfFolder->write();
             }
             $imageFolder = Folder::find(self::$image_folder . '/' . $URLSegment['before']);
             if($imageFolder) {
                $imageFolder->setName($URLSegment['after']);
                $imageFolder->write();
             }
          }
       }

    Here I do exactly what you want and it seems to work. Basicaly i have several AnnualProgramms with several events. So every time the title of an annualprogramm changes i change the URLSegment and remane all folders which are affected by the renaming.

  • alexanderhiam
    Avatar
    Community Member
    2 Posts

    Re: Auto-update image upload directory Link to this post

    Finally got a chance to try this out and it works perfectly, thanks!

    466 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.