我想在我的网站上为表格写一个验证。据我所知,symfony 2允许以下几种方式:
好的,但我的情况是我的网站上有很多表单,我使用表单类型创建表单(例如Project\AcmeBundle\Form\Type\MyFormType
)。
所以对我来说最好的方法是在表单类中创建一个方法来处理其所有字段的验证。类似的东西:
<?php
namespace Project\AcmeBundle\Form\Type;
class UserType extends FormTypeInterface
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('login', 'text', ['required' => false])
->add('password', 'text', ['required' => false]);
$builder->add('Save', 'submit');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Project\AcmeBundle\Entity\Users'
));
}
public function validation()
{
// do something here
}
public function getName()
{
return 'user';
}
} // End UserType
这将是第一个问题。我也对禁用所有其他类型的验证感到好奇 - 我该怎么做?
非常感谢!
答案 0 :(得分:0)
对于第一个问题,您可以使用Callback constraint,这是一个示例:
class MyCustomType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('foo', 'number')
->add('bar', 'number')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver
->setDefaults(array(
'data_class' => 'ENTITY',
'constraints' => array(
new Callback(
array('callback' => array($this, 'validateForm'))
)
)
));
}
/**
* @param $data
* @param ExecutionContextInterface $context
*/
public function validateForm($data, ExecutionContextInterface $context)
{
if ($data->getFoo() < 100) {
$context
->buildViolation('Invalid Foo.')
->atPath('foo')
->addViolation()
;
}
}
public function getName()
{
...
}
}