2012-12-24 58 views
0

的Symfony 2,下面的代碼:形式valdiation失敗

namespace frontend\mainBundle\Form; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\OptionsResolver\OptionsResolverInterface; 
use Symfony\Component\Validator\Constraints\Email; 
use Symfony\Component\Validator\Constraints\Length; 
use Symfony\Component\Validator\Constraints\Collection; 

class ContactForm extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder->add('subject', 'text'); 
     $builder->add('email', 'email'); 
     $builder->add('message', 'textarea'); 
    } 

    public function getName() 
    { 
     return 'contact'; 
    } 
    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $collectionConstraint = new Collection(array(
      'name' => new Length(array("min" => 5)), 
      'email' => new Email(
       array('message' => 'Invalid email address') 
      ), 
      'message' => new Length(array("min" => 5)) 
     )); 

     $resolver->setDefaults(array(
      'constraints' => $collectionConstraint 
     )); 
    } 
} 

DefaultController.php

public function contactAction(Request $request) 
{ 


    $form = $this->createForm(new ContactForm()); 
if ($request->getMethod() == 'POST') { 
    $form->bindRequest($request); 

    if ($form->isValid()) { 
     // perform some action, such as saving the task to the database 
    break; 
     //return $this->redirect($this->generateUrl('task_success')); 
    } 
} 
return $this->render('frontendmainBundle:Default:contact.html.php', array(
    'form' => $form->createView() 
)); 
} 

contact.html.php

<form action="contact" method="post" <?php echo $view['form']->enctype($form) ?> > 
    <?php echo $view['form']->widget($form) ?> 

    <input type="submit" /> 
</form> 

當我提交形式,主題,電子郵件和消息('test','[email protected]','消息文本'),以下錯誤即將到來。

此字段丟失。 主題 此字段不是預期的。 (我想這是電子郵箱)

我確實有一個錯誤信息在我的代碼('無效的電子郵件地址')這是行不通的。爲什麼?

+0

你如何呈現你的模板裏面形式的約束? – tamir

+0

return $ this-> render('frontendmainBundle:Default:contact.html.php',array( 'form'=> $ form-> createView() )); 爲什麼? – craphunter

+0

我的意思是你的contact.html.php是怎麼樣的?你可以發佈一些代碼嗎? – tamir

回答

1

setDefaultOptions你有,而不是主題