Symfony validation on multiple file upload - php

I have a form containing a FileType field. I've set the multiple option to true so the user can upload multiple files at the same time.
$builder->add('myFile', FileType::class, [
'label' => 'upload file',
'multiple' => true,
])
Here is the corresponding property in the Entity connected to this form:
/**
* #Assert\NotBlank()
* #Assert\File(mimeTypes = {"application/pdf", "application/x-pdf", "image/jpeg", "image/png"})
* #ORM\Column(type="array")
*/
private $myFile;
When I submit the form I get the error:
UnexpectedTypeException in FileValidator.php line 168:
Expected argument of type "string", "array" given
I added curly braces in front of File assert so it looks like this:
* #Assert\File{}(mimeTypes = {"application/pdf", "application/x-pdf", "image/jpeg", "image/png"})
Now it doesn't complain when submitting the form. but the file type validation is also not checked.
Any idea how to make the file type working for multiple selected files?

Since you're validating array of File, you need to apply All validator, which will apply inner validators on each element of the array.
Try with something like:
/**
* #Assert\All({
* #Assert\NotBlank(),
* #Assert\File(mimeTypes = {"application/pdf", "application/x-pdf", "image/jpeg", "image/png"})
* })
* #ORM\Column(type="array")
*/
private $myFile;

Related

Symfony2.8: choices_as_values doesn't work

Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList and Symfony\Component\Form\Extension\Core\ChoiceList\LazyChoiceList have been rewritten in Symfony2.8 (details in the post below).
After that, a validation error occurred in Symfony3 and the save of the author selected in the form failed.
I attributed it to the swapping of the Choice Type keys and values.
So, before raising Symfony, I specified chouces_as_values as Type and verified whether it works.
But it didn't work and the result was similar. In other words, can we think that this is not a replacement of key values?
It may be that the rewriting of ChoiceList has failed.
Also, I would like advice on where to debug so that you can understand what is the cause.
Symfony: Unable to reverse value for property path [...]: The choice [...] does not exist or is not unique
https://symfony.com/doc/2.8/reference/forms/types/choice.html#choices-as-values
ArticleType
$ChoiceList = new StaffChoiceLoader($this->staffService, $options['login_staff']);
//$ChoiceList = new StaffChoiceList($this->staffService, $options['login_staff']);
$builder->add("author", "entity", array(
"required" => true,
"class" => "AppBundle:Staff",
"choice_loader" => $ChoiceList,
//"choice_list" => $ChoiceList,
"empty_value" => "Please select",
//Add
"choices_as_values" => true,
));
ArticleEntity
/**
* author
*
* #ORM\ManyToOne(targetEntity="Staff")
* #ORM\JoinColumn(name="author_id", referencedColumnName="id", nullable=true)
*/
protected $author;

how to remove the whitespace in input field of symfony form type?

how to remove the white spaces in input field of Symfony form type?
I want to to throw an error when the user put only white spaces in inputs.
you should use trim in your form type:
$builder
->add('title',null,[
'required' => 'required',
'trim' => true,
])
and in your entity add #Assert\NotBlank :
/**
* #Gedmo\Mapping\Annotation\Versioned
* #Assert\NotBlank
* #ORM\Column(type="string", length=255)
*/
Symfony will handle the rest.

Symfony form: create multiple emails fields

Update
I found in the Symfony docs the answer and an example tutorial to my case: http://symfony.com/doc/current/reference/forms/types/collection.html#basic-usage
How can I assign multiple email fields to a form in Symfony 3.1?
In my entity I have:
/**
* #var array
* #ORM\Column(name="notification_emails", type="array", nullable=true)
*/
private $notificationEmails;
/**
* #return array
*/
public function getNotificationEmails()
{
return $this->notificationEmails;
}
/**
* #param array $notificationEmails
*/
public function setNotificationEmails($notificationEmails)
{
$this->notificationEmails = $notificationEmails;
}
In my form I have:
$builder->add(
'notificationEmails',
CollectionType::class,
array(
'entry_type' => EmailType::class,
'label' => 'Add more emails separated by comma',
'attr' => array(
'multiple' => 'multiple',
),
)
);
But this doesn't work :(
You need Collection type field, only if you are providing multiple email fields for each one email; with some help of javascript and having Add new email button.
If users are going to add emails separated by comma, you don't need a Collection Type field. Keep it simple Text type field with help text as you have done.
Now, in setter [setNotificationEmails], you should split the csv email string to array and feed to ORM. ORM does the rest in order to save in the database.
You should do the vice-versa in getter [getNotificationEmails] (converting array to string). So your form can represent comma separated emails.
In case above doesn't work, as I doubt, the form might not read data from getter. In that case, you can always use a Transformer. It's so useful.

Custom validaton messages not working on Symfony 3

I have the following declaration in my user class (Symfony 3, it's an entity class):
/**
* #ORM\Column(type="string", length=128, unique=true)
* #Assert\NotBlank (
* groups={"registration"},
* message = "test"
* )
* #Assert\Email(
* message = "The email '{{ value }}' is not a valid email.",
* groups={"registration"}
* )
*/
private $email;
Everything works fine, except that I can't set a message, instead of my message ('test' for example) a default "This value should not be blank" is displayed.
Yes, I do have
framework:
validation: { enable_annotations: true }
In my config.yml
Edit: and yes I cleared cache by executing:
sudo php bin/console cache:clear
Edit2: Please note that it actually DOES go through validation, Symfony sees that the email is required, it displays a message if I leave the field empty, it's just that it is not my message, Symfony somehow doesn't see the "message" part.
Edit3: Now, after removing the groups={"registration"} part, as well as changing (in controller)
$errors = $validator->validate($user, null, array('registration'));
to
$errors = $validator->validate($user, null);
(removed array('registration'))
the correct message is displayed. However this is not a solution. I need to use groups.
Edit 4:
I'll get crazy...
If I enter no email, and then:
$validator = $this->get('validator');
$errors = $validator->validate($user, null, array('registration'));
dump($errors);
(Notice the "dump" function call) then I see an incorect message displayed on a page (This value should not be blank) but... when I enter the profiler->debug page (the dev tools at the bottom) then I can see that a correct (my) message is there...
Furthermore in profiler->form errors is this incorect message on the list (as only one item) but... it says it refers to a field named "plainPassword" which is not in the form, and does NOT belong to the "registration" group, so it should not be validated in the first place.
What's going on there?
Can You try this?
/**
* #ORM\Column(type="string", length=128, unique=true)
*
*
* #Assert\NotBlank(
* message = "The box cant be left blank")
*
*
* #Assert\Email(
* message = "The email '{{ value }}' is not a valid email."
*
* )
*/
private $email;

Assert File not validating

I have followed the instructions on the documentation for how to handle file upload using Doctrine.
Image upload works fine but when I upload some other file type, it just lets the file upload even if I have properly set the annotation on the $file property like this:
/**
* #Assert\File(
* maxSizeMessage = "L'image ne doit pas dépasser 5Mb.",
* maxSize = "5000k",
* mimeTypes = {"image/jpg", "image/jpeg", "image/gif", "image/png"},
* mimeTypesMessage = "Les images doivent ĂȘtre au format JPG, GIF ou PNG."
* )
*/
public $file;
I just figured out that the problem was coming from the Product entity. I was adding multiple images to a Product form and I forgot to put the Valid assert to the $images property on the Product entity like so :
/**
* #ORM\ManyToMany(targetEntity="PS\StockBundle\Entity\Image", cascade={"persist"})
* #Assert\Valid()
*/
private $images;
I wrote an article on my blog about this here https://web.archive.org/web/20141004165731/http://www.ennazk.com:80/validate-subforms-in-symfony2/#.Wdt9mBNSwnU
Thanks.
Is {"image/jpg", "image/jpeg", "image/gif", "image/png"}, valid json? because that does not look like a valid json for me (objects in json consist of key=>value pairs.). If json decode fails, then it is possible the entire assertion does not get applied. I don;t know that much about doctrine though, so i might be wrong.

Categories