Non blank file input field in Symfony2 form

后端 未结 3 1715
灰色年华
灰色年华 2020-12-10 13:14

In my Doctrine entity, which is data_class for my form I have a file property defined like this:

/**
     * Image.
     *
     * @Assert\\NotBla         


        
相关标签:
3条回答
  • 2020-12-10 14:00

    You have two ways out this situation and both rely on Callback validators: (Symfony callback)

    Either add boolean named isUpdate to you entity which will not be persisted and will tell validator which operation was attempted. This method is completely described in link above.

    Another way to tackle this is to add Callback validator to your Form type directly. Again, some isUpdate flag will be needed but this time within Form type (pass it via constructor):

    if ( $this->isUpdate == false ){
        $builder->addValidator(new CallbackValidator(function(FormInterface $form){
            if ( $form['image_file']->getData() == NULL ){
                $form->addError(new FormError('You need to specify image file.'));                  
            }
        }));
    }
    

    Maybe there is simplier way to achieve desired validation but I came upon these two few months back.

    Hope this helps...

    0 讨论(0)
  • 2020-12-10 14:11

    I have was in similar situation. I try to edit existing record in database with path to the file. When i edit record i must upload new file, what is not comfortable for users. In my solution i use variable tmp file for file hash and variable file name. All needed operation i made in Action edit class.

    Full example action class in bellow link

    https://github.com/marekz/php_examples/wiki/Symfony-how-to-edit-attachment-form

    0 讨论(0)
  • 2020-12-10 14:20

    You can also use Validation Groups for that. One Validation Group (perhaps default one) will be for create and second for update.

    0 讨论(0)
提交回复
热议问题