我有联系表格,主题应该至少有5个字符但是当我在这个字段中写一个字符并提交表格时,我看到没有错误,为什么,有什么问题?
WebsiteController.php:
namespace Acme\WebsiteBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Acme\WebsiteBundle\Contact\ContactForm;
use Acme\WebsiteBundle\Contact\ContactRequest;
class WebsiteController extends Controller
{
public function contactAction(Request $request)
{
$contactRequest = new ContactRequest();
$form = $this->createForm(new ContactForm(), $contactRequest);
if ($request->getMethod() == 'POST')
{
$form->bindRequest($request);
if ($form->isValid())
{
$contactRequest->send();
$this->get('session')->setFlash('notice', 'Email is ok.');
$this->redirect($this->generateUrl('AcmeWebsiteBundle_homepage'));
}
else
{
$this->get('session')->setFlash('notice', 'Email is wrong.');
}
}
return $this->render('AcmeWebsiteBundle:Website:contact.html.php', array('form' => $form->createView()));
}
}
ContactForm.php:
namespace Acme\WebsiteBundle\Contact;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class ContactForm extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('sender', 'email', array('label' => 'Email', 'trim' => true, 'required' => true, 'max_length' => 50));
$builder->add('subject', 'text', array('label' => 'Temat', 'trim' => true, 'required' => true, 'max_length' => 100));
$builder->add('message', 'textarea', array('label' => 'Wiadomość', 'trim' => true, 'required' => true, 'max_length' => 1000));
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Acme\WebsiteBundle\Contact\ContactRequest',
);
}
public function getName()
{
return 'contact';
}
}
ContactRequest.php:
namespace Acme\WebsiteBundle\Contact;
class ContactRequest
{
/**
* @validation:MinLength(5)
* @validation:MaxLength(100)
* @validation:NotBlank
*/
protected $subject;
/**
* @validation:MinLength(5)
* @validation:MaxLength(1000)
* @validation:NotBlank
*/
protected $message;
/**
* @validation:MaxLength(50)
* @validation:Email
* @validation:NotBlank
*/
protected $sender;
public function setSubject($subject)
{
$this->subject = $subject;
}
public function getSubject()
{
return $this->subject;
}
public function setMessage($message)
{
$this->message = $message;
}
public function getMessage()
{
return $this->message;
}
public function setSender($sender)
{
$this->sender = $sender;
}
public function getSender()
{
return $this->sender;
}
public function send()
{
//.......
}
}
答案 0 :(得分:1)
我认为你正在使用doctrine native validation(?),而在symfony2中你需要使用@Assert来完成该任务。 http://symfony.com/doc/current/book/validation.html
基本上添加Assert命名空间,然后将@validation:
替换为@Assert\