[英]symfony2 form validation
Below is my code for forms 以下是我的表格代码
class PracticeType extends AbstractType {
/**
* Returns the name of this type.
*
* @return string The name of this type
*/
function getName()
{
return "practice";
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Shwetanka\SampleBundle\Entity\Practice',
'csrf_protection' => true,
'csrf_field_name' => '_token',
'intention' => 'practice_item'
);
}
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('name', 'text', array(
'required' => true,
'label' => 'Clinic Name'
));
}
}
My entity 我的实体
/**
* Shwetanka\SampleBundle\Entity\Practice
*
* @ORM\Table(name="practice")
* @ORM\Entity
*/
class Practice
{
/**
* @var integer $id
*
* @ORM\Column(name="practiceId", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string $name
*
* @ORM\Column(name="name", type="string", length=255)
* @Assert\NotBlank()
*/
private $name;
//getters and setters
}
My controller - 我的控制器-
...
$form = $this->createForm(new PracticeType());
if($request->getMethod() == 'POST'){
$form->bindRequest($request);
if($form->isValid()){
$practice = EntityHelper::preparePracticeForSave($form);
return array('hello' => 'world');
}else {
$view = View::create();
$view->setTemplate('ShwetankaSampleBundle:Practice:new_practice.html.twig');
$view->setFormat('html');
$view->setData(array('form' => $form->createView(), 'logout' => true));
return $this->get('fos_rest.view_handler')->handle($view);
}
}
...
When I submit the form I get validation error ($form.isValid() is false)
but when I check $form['name']
i get the value that I entered in the form. 当我提交表单时,我收到验证错误($form.isValid() is false)
但是当我检查$form['name']
我得到了我在表单中输入的值。 I'm not able to understand why validation fails. 我不明白为什么验证失败。 Need help. 需要帮忙。
did you get any errors ? 你有什么错误吗?
render error messages in template with: 使用以下命令在模板中呈现错误消息:
{{ form_errors(form) }}
or access error array in controller: 或访问控制器中的错误数组:
$form->getErrors()
I think it will give you some hints 我想它会给你一些提示
Might you forgot render csrf form tag? 您可能会忘记渲染csrf表单标签吗? You could use form_rest(form)
for this. 您可以form_rest(form)
使用form_rest(form)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.