Visavì
Visavì

Reputation: 2333

How make file field required in symfony2

Yes it is a very simple question but but I am new to symfony 2 and don't found any answer... This is my form:

class CsvUploadType extends AbstractType
{
  public function buildForm(FormBuilder $builder, array $options)
  {
    $builder->add('document', 'file');
  }

  public function getDefaultOptions(array $options)
  {
    $collectionConstraint = new Collection(
        array( 'document' => new File(array('maxSize' => '200k', 'mimeTypes' => array('text/csv','text/plain'))),
            )
        );

    return array('validation_constraint' => $collectionConstraint);
  }

  public function getName()
  {
    return 'csv_upload';
  }
}

Thank you for any help!

NOTE: this is not an Entity based form

Upvotes: 1

Views: 872

Answers (1)

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44841

Here is an example of several constraints on one form field from my project:

/**
 * @param  array $options
 * @return array
 */
public function getDefaultOptions(array $options)
{
    return array(
        'validation_constraint' => new Collection(array(
            'email' => array(
                new NotBlank(array(
                    'message' => 'contact.email.blank'
                )),
                new Email(array(
                    'message' => 'contact.email.invalid'
                ))
            ),
            // ...
        ))
    );
}

Just adapt it to your needs.

Upvotes: 1

Related Questions