Skip to content

Instantly share code, notes, and snippets.

@opalfroot
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save opalfroot/14524bf50f9657ef7d21 to your computer and use it in GitHub Desktop.
Save opalfroot/14524bf50f9657ef7d21 to your computer and use it in GitHub Desktop.
Silverstripe Simple Image Size Upload Validator
<?php
class ImageUpload_Validator extends Upload_Validator{
public $minwidth;
public $minheight;
public function setMinDimensions($width,$height){
if(is_numeric($width) && intval($width)>=0)
$this->minwidth=intval($width);
else
user_error('Invalid minimum width, value must be numeric and at least 0',E_USER_ERROR);
if(is_numeric($height) && intval($height)>=0)
$this->minheight=intval($height);
else
user_error('Invalid minimum height, value must be numeric and at least 0',E_USER_ERROR);
}
public function isValidDimensions() {
//if we cannot determine the image size return false
if(!$dims = getimagesize($this->tmpFile['tmp_name']))
return false;
if(($this->minheight && $dims[1]<=$this->minheight) || ($this->minwidth && $dims[0]<=$this->minwidth))
return false;
return true;
}
public function validate(){
if(!isset($this->tmpFile['name']) || empty($this->tmpFile['name']))
return true;
if(!$this->isValidDimensions()){
$this->errors[]=sprintf('Minimum image size is %s x %s ', $this->minwidth?$this->minwidth.'px':'(ANY)',$this->minheight?$this->minheight.'px':'(ANY)');
return false;
}
return parent::validate();
}
}
<?php
class MyObject extends DataObject{
private static $has_one = array(
'Image' => 'Image'
);
public function getCMSFields()
{
$fields = parent::getCMSFields();
$uploadfield = new UploadField('Image','Main Image');
//setup the new validator
$validator = new ImageUpload_Validator();
$validator->setMinDimensions(1000,70);
$validator->setAllowedExtensions(array('jpg','jpeg', 'gif', 'png'));
$validator->setAllowedMaxFileSize(array('*' => 4194304));
$uploadfield->setValidator($validator);
$fields->addFieldToTab('Root.Main',$uploadfield,'Content');
return $fields;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment