在Symfony REST API项目中,我们正在对传递给端点的参数进行验证。 我试图为此目的使用表单,但它们似乎没有按预期工作。
以此结束点为例:
foreach ($array_date as &$dates) {
// see this &? This means that changing $dates will affect item in $array_date
$dates[11] = ' ';
$dates = date('Y-m-d, H:m:s', strtotime(str_replace('/', '-', $dates)));
}
// Only after array_dates processing - add array to $ip_with_date
$ip_with_date[] = [
'ip' => $ip,
'all_dates' => $array_date
];
接受 companyId 作为参数
我们希望这个参数是必需的和整数。
控制器
GET /users/
表单类型
public function getUsersAction(Request $request)
{
$user = new User();
$form = $this->createForm(new UserType(), $user, array(
'method' => 'GET'
));
$form->handleRequest();
if ( ! $form->isValid()) {
// Send a 400
die('form is not valid');
} else {
die('form is valid');
}
}
validation.yml
class UserType extends FormType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->add('companyId', 'integer');
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver->setDefaults(array(
'data_class' => 'ApiBundle\Entity\User',
'csrf_protection' => false
));
}
/**
* @return string
*/
public function getName()
{
return ''; // if this is not empty, the form is not submitted at all
}
}
config.yml
ApiBundle\Entity\User:
properties:
companyId:
- Type:
type: integer
- NotBlank: ~
- NotNull: ~
问题
$ form->控制器中的isValid()始终为true
答案 0 :(得分:1)
请替换为
$form->handleRequest();
到
$form->handleRequest($request);
我希望它能奏效。