Validating a non-mapped field in a Symfony2 form class when all other fields are mapped to an entity
php, symfony
Solution
You can simply pass property_path=null to data form field. Property path is used to determine related entity field, by setting its value to null you tell the form to not provide field's value to an entity.
// ...
->add('data', 'file', array(
'label' => 'CSV Data File',
'mapped' => false,
'required' => false,
'property_path' => null,
));
// ...
UPD:
To validate this field id prefer create embedded form and pass data field and validation constraints:
class dataType extends AbstractType
// ...
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('data', 'file', array(
'label' => 'CSV Data File',
'required' => false,
));
}
public function getDefaultOptions(array $options)
{
$collection = new Collection(array(
'data' => new NotBlank(),
// ...
));
return array(
'validation_constraint' => $collection,
);
}
//...
And edit entity form class:
->add('data', 'file', array(
'label' => 'CSV Data File',
'mapped' => false,
'required' => false,
));
replace with:
->add('custom', new DataType(), array(
'mapped' => false,
));
Problem
I have a form in my Symfony2 application that is largely used for persisting an entity, but I have added one extra non-mapped field that is used for uploading a file that is then processed and deleted. However, I can't figure out how to validate this additional field. Here it is defined in the `buildForm()` method of my form class: ``` public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name', 'text', array('label' => 'Name')) // ... ->add('data', 'file', array( 'label' => 'CSV Data File', 'mapped' => false, 'required' => false, )); } ``` I initially tried adding the validation for this field to the bundle's `validation.yml` file like so, but as this field is not part of the entity, it threw up an error saying so. ``` My\Bundle\Entity\MyEntity: properties: data: - File: maxSize: 1024k mimeTypes: text/* mimeTypesMessage: Please upload a CSV file ``` My next attempt was to add the constraints within the form class itself, like so, but it appears you can only validate arrays this way, not objects, which I guess is because it's mainly tied to my entity. ``` public function setDefaultOptions(OptionsResolverInterface $resolver) { $collectionConstraint = new Collection(array( 'data' => new File(array( 'maxSize' => '1024k', 'mimeTypes' => 'text/*', 'mimeTypesMessage' => 'Please upload a CSV file', )), )); $resolver->setDefaults(array( 'data_class' => 'My\Bundle\Entity\MyEntity', 'constraints' => $collectionConstraint, )); } ``` From the documentation, it looks like I can use `$this->get('validator')->validateValue();` to validate the extra field on its own, but I'd quite like to validate the whole form at once and display any errors relating to the non-mapped field with the field itself. Does anyone have any ideas?