【发布时间】:2017-09-04 19:12:24
【问题描述】:
我尝试通过将表单验证到 Symfony (3.2) 来验证日期(或日期时间)。
我正在使用 FOSRestBundle 来使用来自请求的 json(因为我尝试开发我的个人 API)
但我尝试了很多格式:
- 2017-04-09
- 17-04-09
- 对于日期时间:
- 2017-04-09 21:12:12
- 2017-04-09T21:12:12
- 2017-04-09T21:12:12+01:00
- ...
但表单无效,我总是收到此错误: 此值无效
我的控制器的功能
public function postPlacesAction(Request $request) {
$place = new Place();
$form = $this->createForm(PlaceType::class, $place);
$form->handleRequest($request);
if ($form->isValid()) {
return $this->handleView($this->view(null, Response::HTTP_CREATED));
} else {
return $this->handleView($this->view($form->getErrors(), Response::HTTP_BAD_REQUEST));
}
}
我的实体
class Place
{
/**
* @var string
*
* @Assert\NotBlank(message = "The name should not be blank.")
*/
protected $name;
/**
* @var string
*
* @Assert\NotBlank(message = "The address should not be blank.")
*/
protected $address;
/**
* @var date
*
* @Assert\Date()
*/
protected $created;
// ....
// Getter and setter of all var
我的实体类型
class PlaceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
$builder->add('address');
$builder->add('created');
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'MyBundle\Entity\Place',
'csrf_protection' => false
]);
}
}
请求示例(我使用的是 Postman)
- 方法:POST
- 标题:应用程序/json
-
正文(原始):
{"place":{"name":"name","address":"an address","created":"1997-12-12"}}
我不确定我使用了正确的格式,或者我的文件中是否缺少任何内容:/
你能不能打开我心中的灯!?! :)
非常感谢您的帮助。 法布里斯
【问题讨论】:
标签: symfony validation date constraints fosrestbundle