长话短说:使用 FOSRestBundle 我正在尝试通过 POST 调用创建一些实体,或通过 PUT 修改现有实体。
这里的代码:
/**
* Put action
* @var Request $request
* @var integer $id Id of the entity
* @return View|array
*/
public function putCountriesAction(Request $request, $id)
{
$entity = $this->getEntity($id);
$form = $this->createForm(new CountriesType(), $entity, array('method' => 'PUT'));
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->view(null, Codes::HTTP_NO_CONTENT);
}
return array(
'form' => $form,
);
} //[PUT] /countries/{id}
如果我调用 /countries/{id} 并使用 PUT 传递像 {"description":"Japan"} 这样的 json,它会使用 id=1 修改我的国家/地区,并放置一个空描述。
相反,如果我尝试使用此方法创建一个新实体:
/**
* Create new Countries (in batch)
* @param Request $request json request
* @return array redirect to get_coutry, will show the newly created entities
*/
public function postCountriesAction(Request $request)
{
$entity = new Countries();
$form = $this->createForm(new CountriesType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirectView(
$this->generateUrl(
'get_country',
array('id' => $entity->getId())
),
Codes::HTTP_CREATED
);
}
return array(
'form' => $form,
);
} //[PUT {"description":"a_description"}] /countries
它给了我一个错误说:
exception occurred while executing 'INSERT INTO countries (description) VALUES (?)' with params [null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'description' cannot be null
所以似乎我无法正确传递绑定到表单的请求。
请注意,如果我按照此处的建议对请求进行 json_decode,它会回复
{
"code":400,
"message":"Validation Failed",
"errors":{
"errors":[
"This value is not valid."
],
"children":{
"description":[
]
}
}
}
有什么建议吗?
谢谢,劳斯