Joshua Bakker
Joshua Bakker

Reputation: 2378

Symfony 4 file upload with entity

I'm working on my module and one part is where you can add new backgrounds to the database to use in a slideshow.

I have a SlideshowBackground entity with 3 properties:

/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", length=150)
 */
private $image;

/**
 * @ORM\Column(type="string", length=100)
 */
private $imageAlt;

And basically, the image is the string of the uploaded file, including the relative path.

I have the following SlideshowBackgroundType as form for the adding slideshow background page:

class SlideshowBackgroundType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('image', FileType::class, [
            'required' => true
        ]);
        $builder->add('imageAlt', TextType::class, ['required' => true]);
    }
}

However, if I submit my form and check $form->getData(), it contains the following data:

SlideshowBackground {#419 ▼
-id: null
-image: "C:\wamp64\tmp\php5B96.tmp"
-imageAlt: "ty"
}

However, this way I can't get the original uploaded file name. I use the following code in my controller:

$slideshowBackground = new SlideshowBackground();
$form = $this->createForm(SlideshowBackgroundType::class, $slideshowBackground);
$form->handleRequest($request);

How can I use SlideshowBackground entity but also be able to have a file uploaded that's not directly mapped to the image?

I tried to modify my image field to the following:

$builder->add('image', FileType::class, [
    'required' => false,
    'mapped' => false
]);

But then I get the same result from $form->getData(), however with the image column as null.

Also, when I try to submit with the last code, I get the following error on image:

This value should not be null.

I know the image property in SlideshowBackground is required, and it should be, but it doesn't work as image isn't defined when submitting with the mapped => false. Any way to go around this problem?

Upvotes: 0

Views: 545

Answers (1)

Cerad
Cerad

Reputation: 48893

I think the OP is still having a problem but not sure. In any event, this works:

class SlideshowBackgroundType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('image', FileType::class, [
            'required' => true,
            'mapped' => false, // *** NEED THIS ***
        ]);
        $builder->add('imageAlt', TextType::class, ['required' => true]);
        $builder->add('upload', SubmitType::class);
    }
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => SlideshowBackground::class,
        ]);
    }
...
class IndexController extends AbstractController
{
    /** @Route("/upload", name="upload") */
    public function upload(Request $request)
    {
        $slideshowBackground = new SlideshowBackground();
        $form = $this->createForm(SlideshowBackgroundType::class, $slideshowBackground);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            /** @var UploadedFile $imageFile */
            $imageFile = $form['image']->getData();
            dump($imageFile);

            // It is up to you to get the original filename per the example in the docs
            $originalFilename = pathinfo($imageFile->getClientOriginalName(), PATHINFO_FILENAME);
            // this is needed to safely include the file name as part of the URL
            //$safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
            //$newFilename = $safeFilename.'-'.uniqid().'.'.$brochureFile->guessExtension();

            $slideshowBackground->setImage($originalFilename); // *** NEED THIS ***
            dump($slideshowBackground);
            ...
        }

Edit by OP:

This answer is correct, however, for future reference / for other people, keep note that if the following code is uncommented in config/packages/validator.yaml, this will not work:

auto_mapping:
            App\Entity\: []

So if this code doesn't work check if the auto_mapping code is commented out.

Edit by the answerer:

I allowed the above edit because apparently it fixed the problem. However, I have been unable to reproduce the issue. Pretty sure there is more code being executed between $form->handleRequest and $form->isValid.

Upvotes: 1

Related Questions