Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Customising the CMS /

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

UploadField and setValidator(). Custom Upload_Validator not functioning as expected.


Go to End


1271 Views

Avatar
Double-A-Ron

Community Member, 607 Posts

24 July 2015 at 9:29am

I have an UploadField for an image that I want to validate (dimensions) before saving to the file system. I have been attempting do do this by manually creating the upload field in the DataObject's getCMSFields() method, and assigning a custom Validator to that before adding it to the CMS. To keep my question simple, I have removed all validation logic from the custom Validator.

Custom Validator

class NewsImageValidator extends Upload_Validator
{

    public function validate()
    {
        if(parent::validate() === false) return false;
        
        // Where my validation stuff will go
        
       return true;
        
    }   
}

Field creation

public function getCMSFields()
    {
        $fields = parent::getCMSFields();
       
        // Manually create the image fields and attach custom validators
        $articleImageField = new UploadField("ArticleImage");
        $articleImageField->setValidator(new NewsImageValidator());
        $fields->addFieldToTab("Root.Main", $articleImageField);
        
        return $fields;
    }

No problems during dev/build or rendering the UploadField in the form. So what I would expect to happen above is exactly the same behaviour as if there were no custom validator at all. E.G. If I added a illegal file, standard behaviour is to display "File extension not allowed" on the UploadField without the upload process even triggering. Which I confirmed using a bogus file "bogus.dump".

Instead, with the Validator added, what happens is the file upload process, and I simply get "Forbidden" message added to the UploadField.

Any Ideas what I'm doing wrong? Is there a known defect? The docs aren't much help and examining this use of an Upload_Validator, I seem to be doing everything exactly the same.