0

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?

5
  • Look at the controller code in the docs example. Be sure to filter the results of getClientOriginalName() since it could be an attack vector. Commented Aug 22, 2019 at 13:33
  • @Cerad I did look there but again I couldn't figure it out as it gives an additional problem. My form uses my entity which has a property image which is required, and since when submitting it is null, it throws errors. However, image should be required AFAIK as backgrounds need to have an image specified. Commented Aug 22, 2019 at 13:35
  • Nevermind, I detected my stupidity, I got the right data and I found the problem. Thanks anyways Commented Aug 22, 2019 at 13:44
  • Did it have to do with not setting mapped to false? Just curious. Commented Aug 22, 2019 at 13:47
  • Actually it doesn't work. I changed my image input in the form builder to imageupload, it does add a new unmapped input type. However, my form doesn't work as image in SlideshowBackground entity is null which cannot happen. Thus, $form->isSubmitted() && $form->isValid() will return false. I only detected me looking at $form->getData and that only returns the entity (and not extra fields). So I'm able to get the uploaded image from the form but I cannot submit my form Commented Aug 22, 2019 at 13:51

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

9 Comments

This gives the error This value should not be null. on the image upload field. And this means $form->isSubmitted() && $form->isValid() is also false. This is most likely because image is a property in SlideshowBackground entity that is required but not set.
@JoshuaBakker You have something else going on. I tested the code before posting and it works as expected. The mapped attribute is smart enough to allow the property to pass the "is not null" test. Here is a github repo of my working code: github.com/cerad/upload
I see your SlideshowBackground isn't a database entity class. Maybe that's the problem. I just realize I never said it was a database entity class.
It basically is. I just never added the annotations. The forms component does not care about doctrine annotations. If you have some additional validation going on somewhere (perhaps a form listener or something) then that could be causing the problem.
Not really, I have created the form using my form type class (extending from AbstractType) and I've used the entity class constructor in the createform as data. And I do get the error and I don't use anything else that could break it AFAIK.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.