Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

validation - Non blank file input field in Symfony2 form

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

/**
     * Image.
     *
     * @AssertNotBlank
     * @AssertFile
     * @AssertImage(minWidth="138", minHeight="96")
     */
    protected $file;

Also, added it to form type with ->add('file', 'file')...

Creating entity works perfect, but the problem is when I use form to update this entity. It asks for file again, since it has @AssertNotBlank. Since I have other fields in this form, I don't want to reupload image on every update.

When I remove @AssertNotBlank, everithing works fine, but I want this file field to be mandatory.

Any idea?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...