如何在控制器中验证没有实体的表单?

时间:2014-05-14 08:32:18

标签: php forms validation symfony

我有一个发送电子邮件的基本表单:

<form action="{{ path('user_send_mail') }}" method="post" enctype="multipart/form-data">

  <input name="email_to" type="email" class="form-control" placeholder="To" required>

  <input name="email_cc" type="email" class="form-control" placeholder="Cc">

  <textarea name="message" id="email_message" class="form-control" placeholder="message"     style="height: 120px;" required></textarea>

  <input type="file" name="attachment"/>

  <p class="help-block">Max. 2MB</p>

  <button type="submit" class="btn btn-primary pull-left"><i class="fa fa-envelope"></i> Send the email</button>

</form>

我的控制器中的一项操作是验证数据并发送邮件,但验证不起作用..

use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\Validator\Constraints\NotBlank;

public function sendMailToUserAction(Request $request)
{
        $form = $this->createFormBuilder(null)
            ->add('email_to', 'email', array(
                'required' => true,
                'constraints' => new Email()
            ))
            ->add('email_cc', 'email', array(
                'required' => false,
                'constraints' => new Email()
            ))
            ->add('message', 'textarea', array(
                'required' => true,
                'constraints' => new NotBlank()
            ))
            ->add('attachment', 'file', array(
                'required' => false,
                'constraints' => new File()
            ))
            ->getForm();

        $form->handleRequest($request);

        if ($form->isValid()) {
            $data = $form->getData();
            var_dump($data);exit;
        } else {
            var_dump("error");exit;
        }
}  

当我提交表单时,我总是得到#34;错误&#34;,所以验证不起作用,但我不知道为什么......我已经阅读了很多关于此的主题但我卡住了..

编辑:如果我使用$form->getErrorsAsString()代替var_dump("error");exit;打印表单错误,我就明白了:

string(97) "email_to: No errors email_cc: No errors message: No errors attachment: No errors "

1 个答案:

答案 0 :(得分:0)

请注意:http://symfony.com/doc/current/book/forms.html#using-a-form-without-a-class它认为您必须传递包含您要验证的字段名称的数组(它类似于默认值)

页。秒。为什么不使用Simple PHP Object呢? Symfony2表单字段名称应包含类似(例如)的数据块:data [email_to]而不是email_to