验证没有任何实体的文件上载

时间:2014-10-27 09:59:17

标签: validation symfony

我在symfony" ImportType"中创建了一个新的表单类型。此表单类型仅包含两个字段,即文件输入和提交按钮。

在我的控制器中,我将验证发布的文件。我将检查文件mimetype和filesize。但是,如何在没有任何实体的情况下验证这一点?

如果我使用验证器服务进行验证,我不知道如何为mimetype和文件大小注入验证信息?

use Symfony\Component\Validator\Constraints\File;

public function importAction(Request $request) 
{
    // Create new form and map this with the user object
    $form = $this->createForm($this->get('form.type.import'))->add('send', 'submit');

    // Handle user request
    $form->handleRequest($request);

    $file = $form->get('attachment');

    $fileContraints = new File();
    $fileContraints->maxSizeMessage = 'msg.validator.file.import.maxFileSize';
    $fileContraints->mimeTypes      = 'msg.validator.file.import.mimeType';

     /** @todo set options for file mimetype and max file size **/
    $file = $form->get('attachment');

      // use the validator to validate the value
        $errorList = $this->get('validator')->validateValue(
            $file,
            $fileContraints
        );
}

1 个答案:

答案 0 :(得分:2)

您可以在控制器中对其进行验证并手动添加错误:

$file = $form->get('attachment');

$fileContraints = new File();
$fileContraints->maxSizeMessage = 'msg.validator.file.import.maxFileSize';
$fileContraints->mimeTypes      = 'msg.validator.file.import.mimeType';

$errorList = $this->get('validator')->validateValue($file, $fileContraints);

if (count($errorList)) {
    $errorMessage = $errorList[0]->getMessage();
    $file->addError($errorMessage);

    // adding an error causes the form to be invalid:
    $form->isValid(); // now returns false
}

请注意,验证程序API在2.5中已更改:

// pre 2.5
$errorList = $this->get('validator')->validateValue($file, $fileContraints);
// 2.5 and higher
$errorList = $this->get('validator')->validate($file, $fileContraints);