Fab*_*ice 5 validation date constraints symfony fosrestbundle
我尝试通过 Symfony (3.2) 中的表单验证来验证日期(或日期时间)。
我正在使用 FOSRestBundle 来使用请求中的 json (因为我尝试开发我的个人 API)
但我尝试了很多格式:
但表单无效,我总是收到此错误:此值无效
我的控制器的功能
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));
}
}
Run Code Online (Sandbox Code Playgroud)
我的实体
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
Run Code Online (Sandbox Code Playgroud)
我的实体类型
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
]);
}
}
Run Code Online (Sandbox Code Playgroud)
请求示例(我正在使用 Postman)
身体(原始):
{"place":{"name":"name","address":"an address","created":"1997-12-12"}}
Run Code Online (Sandbox Code Playgroud)我不确定我使用的格式是否正确,或者我的文件中是否缺少任何内容:/
请你打开我心中的灯好吗?!:)
非常感谢你的帮助。法布里斯
您的表单类型中的字段存在问题created。当您created使用语法添加字段时,将应用$builder->add('created');默认类型,并且输入数据是字符串,而不是实例。Symfony\Component\Form\Extension\Core\Type\TextType1997-12-12DateTime
要解决此问题,您应该传入DateType第二个参数:$builder->add('created', 'Symfony\Component\Form\Extension\Core\Type\DateType');。这种表单类型有一个转换器,它将输入数据转换1997-12-12为DateTime实例。
有关 Symfony 表单类型的更多信息,请查看表单类型参考
| 归档时间: |
|
| 查看次数: |
6536 次 |
| 最近记录: |