Wolf Vollprecht
Asylstrasse 127
8032 Zürich

TEL: +41 76 729 39 99

MAIL: w.vollprecht@gmail.com

Using the UploadField in Silverstripe

Wolf Vollprecht // 12 October 2012

In Silverstripe 3.0 using the UploadField with relations is not as intuitive as one would hope. So I did this little write-up on how to use the UploadField, which is after all really great and an incredibly fast way to »throw« some images on your website.

Adding images to a Page

Connecting some images to a page object is something very common, e.g. for a slideshow. Since version 3.0 this has become even easier, thanks to the UploadField.

Setting up the relationship

If you want to have one or more images on your Page Object, make a connection with $many_many (that way you can use one image on more than one Page). Then adding an UploadField to getCMSFields() and it's ready.

class Page extends SiteTree {
    static $many_many = array(
        'Images' => 'Image'
    );

    function getCMSFields() {
        $fields = parent::getCMSFields();
        $uploadfield = new UploadField('Images', 'Upload Images', $this->Images);
        $uploadfield->setFolderName('Portfolio');       
        $fields->addFieldToTab('Root.Main', $uploadfield);
        return $fields;
    }
}    

You can additionally limit the number of files you allow on a specific relation with:

$uploadfield->setConfig('allowedMaxFileNumber', 5);

and you can also limit the filetypes that are allowed to upload with

$uploadfield->getValidator()->setAllowedExtensions(array('jpg', 'jpeg', 'png', 'gif'));

Using the images in a template

To loop through all the images in your relationship:

<% loop Images %>
    $Image.SetWidth(800)
<% end_loop %>

More information

There is a lot more information about what you can do with your images here: Image Reference Documentation.

Thanks

Thanks for reading! If you want more of that stuff, consider following me on twitter