Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

symfony - missing data from FormEvents PRE_SUBMIT to SUBMIT listener

I have a Symfony 4 form where I'd like to manipulate a field's value.

I have more listeners attached to it: PRE_SET_DATA, PRE_SUBMIT and SUBMIT (last one for verification purposes only).

To be more precise, it's a file uploader field in a modification form, so if the user left empty, then I want to use the value was before (no changes).

$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
  $data = $event->getData();
  $event->getForm()->get('picture')->setData($data->getPicture());

in the example above, i've set the field's value with the stored one (from entity), that's working

$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
  $data = $event->getData();  // array
  $entity = $event->getForm()->getData();
  if (empty($data['picture']) && !empty($entity)) {
    $data['picture'] = $entity->getPicture();
    $event->setData($data);
  }

dumping $event still contains the data, that's fine so far.

   $builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) {
      dump($event);
    });

but the SUBMIT event forgets all, and at this point i'm unable to add it.

The goal is to set up picture field's value that goes towards the SUBMIT and not disappears.

question from:https://stackoverflow.com/questions/65840980/missing-data-from-formevents-pre-submit-to-submit-listener

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My assumption is that your data is removed between events on purpose by FileType. It's because FileType expect from user object of type:

SymfonyComponentHttpFoundationFileUploadedFile

But probably you have only file name in your entity instead of this object. And thats why it is ignored.

On top of that you can't prepopulate HTML with data from server. It's impossible by the specification.

Solution

Show empty file upload input. If picture exists show it to user right below it in template. This way user will know that image is already uploaded.

In controller check if user upload anything through you filed. And only if there is any file, process it. This requires to set upload field to be mapped=false and you should handle it yourselves.

On top of that, probably, you should add user ability to remove image. But it's up to yours business model.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...