4

I'm new to Silverstripe and am having trouble finding the answer to my issue in the documentation or on SO.

I'm using Silverstripe purely as a CMS: there is no website as a frontend.

I have the simplest DataObject Product and a ModelAdmin ProductAdmin as follows:

class Product extends DataObject
{

  private static $db = array(
    'Name' => 'Varchar',
    'Copy' => 'Text'
  );

  private static $has_one = array(
    'MyImage' => 'Image'
  );

}


class ProductAdmin extends ModelAdmin
{

  private static $managed_models = array(
    'Product'
  );

  private static $url_segment = 'product';

  private static $menu_title = 'Product';

}

After a /dev/build, my admin panel is built and I can upload a high resolution image to the 'Uploads' directory as usual.

I would like on upload for the CMS to resample the image into several different sizes, whilst also retaining the original. The new and original images also need to be saved to a location where the FlushGeneratedImagesTask will not delete them. From looking through the documentation, I know that images can be resized easily, but it's not clear to me where (or how) to add the custom functionality required. Can anyone help?

(I think Silverstripe 3.1 - resize image on upload comes closest to answering this, but there is a step missing that shows how to get the CMS to use the new/overridden functionality.)

I am using Silverstripe version 3.1

Community
  • 1
  • 1
MarkS
  • 127
  • 6

1 Answers1

2
  1. Create a new class MyImage that extends Image.
  2. Create a function onBeforeWrite() in your MyImage class.
  3. Inside this function, make a new image $image = Image::create(). This is where you'll set the filename, name, title, ParentID, etc of your resampled images
  4. Resize your image with $image->SetWidth(...)
  5. Update your array Product::$has_one to say MyImage => MyImage
cryptopay
  • 1,084
  • 6
  • 7
  • Thanks for answering Elliot. I still seem to be missing a step here. Am I subclassing `Image` to get `MyImage`? What internal mechanism am I using to get SS to recognise this new class in place of Image during the standard upload? Thanks in advance! – MarkS Sep 09 '15 at 13:25
  • Sorry, I assumed that MyImage was already a subclass of Image. Because Image inherits from DataObject, `onBeforeWrite` will run automatically. I will edit my answer to reflect this – cryptopay Sep 10 '15 at 02:21
  • Perfect. Thanks again! – MarkS Sep 11 '15 at 14:25
  • One more thing. I somehow need to get my current image `$this` into `$image` as I obviously can't save `$image` until it has some content in it to save! I've assumed I am supposed to do the write of `$image` inside `onBeforeWrite()` and leave the `parent::onBeforeWrite()` to do its work on saving the original image. – MarkS Sep 16 '15 at 11:40
  • You could use `onAfterWrite` to do the resampling, after the original Image has been written. – cryptopay Sep 17 '15 at 00:32