我试图做的事情很简单,因为日期字段不能设置在"现在"值。我强调这个日期字段没有链接到任何实体。即使我将它设置在两个地方,Symfony仍然会忽略约束:
1。约束在类定义中设置
这是我做过的第一件事。我决定将此约束直接放在我定义此日期字段的位置
namespace Asmox\BubblechecklistBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\LessThanOrEqual;
class DeadlineType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('date', 'datetime',array(
'mapped' => false,
'date_format' => 'dd MMMM yyyy',
'constraints' => array(
new LessThanOrEqual("now")
)
));
}
2。在validation.yml文件中设置约束
我还将约束添加到单独的文件中,因为第一种方式没有给出结果:
Asmox\BubblechecklistBundle\Form\Type\DeadlineType:
properties:
date:
- LessThanOrEqual: now
我确保在两个配置文件中都启用了验证(对于prod和dev):
validation: { enabled: true, enable_annotations: true }
但是每当我尝试提交早于现在的日期表格时,Symfony就会通过它。我不知道自己能做些什么。请查看来自Controller的粘贴:
public function newTaskAction(Request $request)
{
// ...
$form = $this->createForm(new TaskType());
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
// Add new task...
// Redirect to the task list
$this->addFlash('notice', 'I've added new task!');
return $this->redirectToRoute('tasksList');
}
else {
// Create view with form if form is not validate
$request = $this->getRequest();
$request->setLocale('pl');
if ($mobileDetector->isMobile())
$template = 'AsmoxBubblechecklistBundle:Task:taskFormPhone.html.twig';
else
$template = 'AsmoxBubblechecklistBundle:Task:taskForm.html.twig';
return $this->render($template, array('form'=>$form->createView()));
}
}
else {
// Create view with form if request isn't POST
$request = $this->getRequest();
$request->setLocale('pl');
// Utwórz widok
if ($mobileDetector->isMobile())
$template = 'AsmoxBubblechecklistBundle:Task:taskFormPhone.html.twig';
else
$template = 'AsmoxBubblechecklistBundle:Task:taskForm.html.twig';
return $this->render($template, array('form'=>$form->createView()));
}
}
怎么了?