我尝试使用Symfony 3和FOSRestBundle实现API Rest。 我的POST / PUT / PATCH动作不起作用。
这是补丁操作的示例。
那是我的代码:
表格:
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class SchoolType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('email')
->add('address')
->add('zip')
->add('city')
->add('url')
->add('siret')
;
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\School',
));
}
}
控制器:
/**
* Update a School entity.
*
* CURL command :
* curl -i -H "Content-Type: application/json" -X PUT -d '{"name" : "TEST", ...}' http://domain_name.com/api/entity/1
*
* @ApiDoc(
* resource=true,
* description="Update a school",
* statusCodes={
* 200="Successful"
* }
* )
*
* @param Request $request
* @param $entity
*
* @return Response
*/
public function putAction(Request $request, School $entity)
{
try {
$request->setMethod('PATCH'); //Treat all PUTs as PATCH
$form = $this->createForm(SchoolType::class, $entity, array("method" => $request->getMethod()));
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->flush();
return $entity;
}
return FOSView::create(array('errors' => $form->getErrors(true, false)), Codes::HTTP_INTERNAL_SERVER_ERROR);
} catch (\Exception $e) {
return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR);
}
}
我总是得到这个回复:
{
"errors": {
"form": {
"children": {
"name": {},
"email": {},
"address": {},
"zip": {},
"city": {},
"url": {},
"siret": {}
}
},
"errors": []
}
}
$ form-> isValid()始终返回false。
我从Symfony开始,我不知道该怎么做。
由于
答案 0 :(得分:1)
我找到了解决方案。 问题是我没有提交表格。 所以不要使用
$form->handleRequest($request);
我用
$form->submit($request->request->all(), false);