Skip to content
Permalink
Browse files

NEW: Implement accept attribute in FileField (closes #7279)

  • Loading branch information...
kinglozzer committed Oct 3, 2017
1 parent 4cbaf7c commit 43ec2f87eda5e8e2dbacc5679520da6eac3a8610
Showing with 58 additions and 2 deletions.
  1. +39 −1 src/Forms/FileField.php
  2. +19 −1 tests/php/Forms/FileFieldTest.php
@@ -2,10 +2,11 @@
namespace SilverStripe\Forms;
use SilverStripe\Assets\File;
use SilverStripe\Control\HTTP;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DataObjectInterface;
use SilverStripe\Assets\File;
/**
* Represents a file type which can be added to a form.
@@ -85,6 +86,43 @@ public function Field($properties = array())
return parent::Field($properties);
}
public function getAttributes()
{
$attributes = parent::getAttributes();
$accept = $this->getAcceptFileTypes();
if ($accept) {
$attributes = array_merge(['accept' => implode(',', $accept)], $attributes);
}
return $attributes;
}
/**
* Returns a list of file extensions (and corresponding mime types) that will be accepted
*
* @return array
*/
protected function getAcceptFileTypes()
{
$extensions = $this->getValidator()->getAllowedExtensions();
if (!$extensions) {
return [];
}
$accept = [];
$mimeTypes = HTTP::config()->uninherited('MimeTypes');
foreach ($extensions as $extension) {
$accept[] = ".{$extension}";
// Check for corresponding mime type
if (isset($mimeTypes[$extension])) {
$accept[] = $mimeTypes[$extension];
}
}
return array_unique($accept);
}
/**
* @param DataObject|DataObjectInterface $record
*/
@@ -2,6 +2,7 @@
namespace SilverStripe\Forms\Tests;
use ReflectionMethod;
use SilverStripe\Dev\FunctionalTest;
use SilverStripe\Control\Controller;
use SilverStripe\Forms\FileField;
@@ -11,7 +12,6 @@
class FileFieldTest extends FunctionalTest
{
/**
* Test a valid upload of a required file in a form. Error is set to 0, as the upload went well
*
@@ -39,6 +39,24 @@ public function testUploadRequiredFile()
$this->assertTrue($form->validationResult()->isValid());
}
/**
* @skipUpgrade
*/
public function testGetAcceptFileTypes()
{
$field = new FileField('image', 'Image');
$field->setAllowedExtensions('jpg', 'png');
$method = new ReflectionMethod($field, 'getAcceptFileTypes');
$method->setAccessible(true);
$allowed = $method->invoke($field);
$expected = ['.jpg', '.png', 'image/jpeg', 'image/png'];
foreach ($expected as $extensionOrMime) {
$this->assertContains($extensionOrMime, $allowed);
}
}
/**
* Test different scenarii for a failed upload : an error occured, no files where provided
* @skipUpgrade

0 comments on commit 43ec2f8

Please sign in to comment.
You can’t perform that action at this time.