rol*_*ree 8 post put request symfony fosrestbundle
长话短说:使用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}
Run Code Online (Sandbox Code Playgroud)
如果我通过PUT调用/ countries/{id}并传递像{"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
Run Code Online (Sandbox Code Playgroud)
它给我一个错误说:
exception occurred while executing 'INSERT INTO countries (description) VALUES (?)' with params [null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'description' cannot be null
Run Code Online (Sandbox Code Playgroud)
所以似乎我无法正确传递绑定到表单的请求.
请注意,如果我按照此处的建议对json_decode请求进行回复,请回复
{
"code":400,
"message":"Validation Failed",
"errors":{
"errors":[
"This value is not valid."
],
"children":{
"description":[
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
任何建议?
谢谢,劳斯
rol*_*ree 21
我解决了:)
这就是它之前没有工作的原因:
在我的表单定义中,名称是"zanzibar_backendbundle_countries".
public function getName()
{
return 'zanzibar_backendbundle_countries';
}
Run Code Online (Sandbox Code Playgroud)
因此,要将请求绑定到此表单,json应该如下所示:
{"zanzibar_backendbundle_countries": [{"description": "Japan"}]}
Run Code Online (Sandbox Code Playgroud)
因为我希望它像
{"id":1,"description":"Italy"}
Run Code Online (Sandbox Code Playgroud)
我不得不从表单中删除名称:
public function getName()
{
return '';
}
Run Code Online (Sandbox Code Playgroud)
一般来说,如果你想发布一个像占位符一样的json
"something":{"key":"value"}
Run Code Online (Sandbox Code Playgroud)
你的表格名称必须是"某事"