Hi,
I've encountered a problem with entity update using this bundle.
HTML5 validation throws required field error when there is already uploaded file.
Mappings:
Config:
vich_uploader:
db_driver: orm
mappings:
foo_image:
uri_prefix: /uploads/foo
upload_destination: %kernel.root_dir%/../web/uploads/foo
Entity:
FooBundle\Entity\Foo:
type: entity
table: null
id:
id:
type: integer
generator:
strategy: AUTO
fields:
image:
type: string
length: 255
lifecycleCallbacks: { }
Vich:
FooBundle\Entity\Foo:
imageFile:
mapping: foo_image
filename_property: image
<?php
namespace FooBundle\Entity;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class Foo
{
/**
* @var int
*/
private $id;
/**
* @var string
*/
private $image;
/**
* @var UploadedFile
*/
private $imageFile;
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param int $id
*
* @return Foo
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getImage()
{
return $this->image;
}
/**
* @param string $image
*
* @return Foo
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* @return UploadedFile
*/
public function getImageFile()
{
return $this->imageFile;
}
/**
* @param UploadedFile $imageFile
*
* @return Foo
*/
public function setImageFile($imageFile)
{
$this->imageFile = $imageFile;
return $this;
}
}
Form
<?php
namespace FooBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class FooType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(
'imageFile',
'vich_image',
[
'label' => 'Image'
]
);
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
[
'data_class' => 'FooBundle\Entity\Foo'
]
);
}
/**
* @return string
*/
public function getName()
{
return foobundle_foo';
}
}
Upload work's fine on create entity, but when I add
'required' => true
to form and try to edit entity I can't submit form due to validation error.
I have just ran into the same problem. Any fixed planned or on it's way?
+1
Well, that's the point of adding 'required' => true, no?
In case of editing an entity, this field should be filled with some data, right?
An image should be displayed and a checkbox should be provided to delete the image. But the upload field itself can not be filled.
So there is no way to make that field required?
True. Image is there, also checkbox. But if upload field (or any fake-field) is empty, you simply can't submit form ;)
Sure there is: 'required' => true in the form type and proper validation in the model.
The same works if you only want this field to be required when there isn't already a value: configure the form type with 'required' => false and also check the validation layer.
The validation isn't handled at all by this bundle, it's all plain "_Symfony code_" ;)
I don't want it required only when creating new entity :P I want this field also be required when I'm chaging another property in this entity, i.e. movie title. Why image field should not be required then?
C'mon, it's already there! ;)
If you already have an image, using 'required' => false won't force the user to re-upload it each time he makes a change to another field of the form. If you don't upload anything, the old image will be left untouched.
Most of the time, when a new entity is created I want the image to be required (so 'required' => true).
But when I edit an entity, I want the user to be able to choose another image or just to edit the other fields (so 'required' => false).
So you basically allow user to remove image from entity. This is not expected behavior.
One way that could work is to set 'novalidate' attribute on field...
Your solution requires to pass argument to form (wich is common to both create/edit action) that determine type of action?
So you basically allow user to remove image from entity. This is not expected behavior.
If you don't want that, you can set allow_delete to false, it will prevent the "delete checkbox" from being displayed. So either the user changes the image or it's left untouched.
Your solution requires to pass argument to form (wich is common to both create/edit action) that determine type of action?
Passing an argument/option can be a solution. Distinct form types for distinct actions can be another :)
You are wrong. If user do not want to change that image in edit action, he left file field empty (it is not being 'filled' by entity data), and since the field is required he can't submit the form.
That's why I set 'required' => false for edit actions (and I also check that the server validation is well configured).
You know that this is a workaround for unexpected behaviour?
I don't think that having separate forms for create and update actions is a good pattern (think about DRY).
You know that this is a workaround for unexpected behaviour?
From my point of view, the behavior described in this issue is expected :)
I don't think that having separate forms for create and update actions is a good pattern (think about DRY).
So don't create separate forms ;)
We've got different pov's ;)
For me expected behavior is: even if I don't upload anything new while editing entity, validation goes through and entity is edited without changing an image ;)
For me expected behavior is: even if I don't upload anything new while editing entity, validation goes through and entity is edited without changing an image ;)
Yep, that's exactly what happens when you use 'required' => false :)
This option only impacts client-side validation (ie: HTML attributes on the upload field).
+1 I also think, that's a problem. Error shouldn't occur, when image is uploaded...
How to manage with this problem when I'm using EasyAdmin bundle?
A file input can't be pre-filled, so you can't use the html5 required validation when editing, that's how our browsers implement html, it's not a VichUploaderBundle issue.
@K-Phoen i have a question though, i'd like to know the correct way to use the symfony validation on a required file. If i set a NotBlank on the filename property, it's invalid when i create the entity, if i set the NotBlank on the file property, it's not valid when i update the entity.
How do you do this ?
Are we supposed to set the NotBlank depending on the situation ?
@jcrombez:
If this is still relevant to you, could you specify what exactly you are trying to achieve? You should not have to use the NotBlank annotation. By default, the file input is required, and if you don't want this, you add 'required' => false to the file input field in your form type.
I'm not working on the related project anymore and my memory will not be enough to know if your answer would have solved my interrogation ^^'
Alright, maybe it'll help some other people :-)
2016-10-19 12:33 GMT-04:00 Jérémy CROMBEZ [email protected]:
I'm not working on the related project anymore and my memory will not be
enough to know if your answer would have solved my interrogation ^^'—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/dustin10/VichUploaderBundle/issues/468#issuecomment-254867931,
or mute the thread
https://github.com/notifications/unsubscribe-auth/APKwZHOcp6KMluVlo8gKQ62u561sThCdks5q1kZagaJpZM4GYMGR
.
@nico-ha Did you fix this issue?
Hi @ceesvanegmond, unfortunately I'm no longer working on this either, so I can't help you here.
For anyone having this issue, I fixed this by creating a new type for the edit form, set required to false to the vich file type, and added validation groups for the entity
// formtype
->add('imageIconFile', VichFileType::class, [
'required' => false,
])
// entity
/**
* @Vich\UploadableField(mapping="app.setting.mapping.assets.images", fileNameProperty="imageIcon")
* @Assert\NotBlank()
* @Assert\Type(type="Symfony\Component\HttpFoundation\File\UploadedFile", groups={"edit"})
* @Assert\File(
* maxSize="1M",
* mimeTypes={"image/png", "image/jpeg", "image/pjpeg"},
* mimeTypesMessage="Please upload a valid image",
* groups={"edit"}
* )
*/
And in the form type default options set edit to the validation_groups 'validation_groups' => array('edit'),
This way the file and type checks are still validated
@akalineskou - Hi, I have related issue with this bundle - I'm using Assert annotations like Assert\File or Assert\Image and VichImageType as Form Type - after submitting the form I have validation errors but the file is also uploaded. Maybe you have some solution for this issue?
Here is my code snippet with property configuration (the same validation in all forms):
```/**
* @Vich\UploadableField(mapping="avatars", fileNameProperty="avatar")
* @Assert\Image(
* mimeTypes = {"image/jpg", "image/gif", "image/png", "image/jpeg"},
* mimeTypesMessage = "user.form_new.avatar.ext",
* minWidth = 50,
* minWidthMessage = "user.form_new.avatar.dimensions",
* maxWidth = 50,
* maxWidthMessage = "user.form_new.avatar.dimensions",
* minHeight = 50,
* minHeightMessage = "user.form_new.avatar.dimensions",
* maxHeight = 50,
* maxHeightMessage = "user.form_new.avatar.dimensions",
* allowLandscape = false,
* allowPortrait = false,
* allowLandscapeMessage = "user.form_new.avatar.dimensions",
* allowPortraitMessage = "user.form_new.avatar.dimensions"
* )
* @Assert\File(
* maxSize = "1M",
* maxSizeMessage = "user.form_new.avatar.max_mb"
* )
*/
private $avatarFile;
For anyone who's blocked by the AssertNotBlank, I made my own Validator for Vich extending the AssertNotBlank. I skip the AssertNotBlank verification if the target (containing the file path) is not empty :
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraints\NotBlank;
/**
* @Annotation
*/
class NotBlankVich extends NotBlank
{
public $target = null;
}
<?php
namespace Site\Validator;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\NotBlankValidator;
class NotBlankVichValidator extends NotBlankValidator
{
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint)
{
if ($constraint instanceof NotBlankVich && $constraint->target) {
$targetValue = PropertyAccess::createPropertyAccessor()->getValue($this->context->getObject(), $constraint->target);
if (!empty($targetValue)) {
return;
}
}
parent::validate($value, $constraint);
}
}
/**
* @Vich\UploadableField(mapping="photo", fileNameProperty="photo")
* @Assert\File(mimeTypes = {"application/pdf", "image/jpg", "image/jpeg"})
* @NotBlankVich(groups={"example_group"}, target="photo")
* @var File
*/
private $photoFile;
/**
* @var string
* @ORM\Column(name="photo", type="text", nullable=true)
*/
private $photo;
Most helpful comment
We've got different pov's ;)
For me expected behavior is: even if I don't upload anything new while editing entity, validation goes through and entity is edited without changing an image ;)