Skip to content

Commit

Permalink
Extend Symfony File type for full-capabilities.
Browse files Browse the repository at this point in the history
  • Loading branch information
Bozhidar Hristov committed Jul 20, 2020
1 parent 9b74fc6 commit 7294652
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 17 deletions.
18 changes: 10 additions & 8 deletions Form/EventListener/FileUploadListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
namespace Arxy\FilesBundle\Form\EventListener;

use Arxy\FilesBundle\Manager;
use Arxy\FilesBundle\Model\File;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
Expand All @@ -15,6 +14,7 @@ class FileUploadListener implements EventSubscriberInterface
{
/** @var Manager */
private $fileManager;
private $data;

/**
* FileUploadListener constructor.
Expand All @@ -29,23 +29,25 @@ public function __construct(Manager $fileManager)
public static function getSubscribedEvents()
{
return [
FormEvents::POST_SET_DATA => 'postSetData',
FormEvents::SUBMIT => 'submit',
];
}

public function postSetData(FormEvent $event)
{
$this->data = $event->getData();
}

public function submit(FormEvent $event)
{
/** @var UploadedFile $uploadedFile */
$uploadedFile = $event->getForm()->get('file')->getData();
$uploadedFile = $event->getData();

if ($uploadedFile && $uploadedFile->isValid()) {
if ($uploadedFile instanceof UploadedFile && $uploadedFile->isValid()) {
$event->setData($this->fileManager->upload($uploadedFile));
} else {
if ($event->getData() instanceof File) {
$event->setData($event->getData());
} else {
$event->setData(null);
}
$event->setData($this->data);
}
}
}
20 changes: 11 additions & 9 deletions Form/Type/FileType.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

class FileType extends AbstractType
{
Expand All @@ -28,18 +29,19 @@ public function __construct(Manager $fileManager)

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add(
'file',
\Symfony\Component\Form\Extension\Core\Type\FileType::class,
[
'mapped' => false,
'label' => false,
]
);

$builder->addEventSubscriber(new FileUploadListener($this->fileManager));
}

public function getParent()
{
return \Symfony\Component\Form\Extension\Core\Type\FileType::class;
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefault('data_class', null);
}

public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['file'] = $form->getData();
Expand Down

0 comments on commit 7294652

Please sign in to comment.