我是symfony框架的新手 . 我正在尝试使用FOSRest包创建web服务,但是当我尝试使用json为一个实体实现POST方法时遇到了问题 .
测试:
public function testJsonPostNewTesteAction(){
$this->client->request(
'POST',
'/api/teste/new',
array(),
array(),
array(
'Content-Type' => 'application/json',
'Accept' => 'application/json'
),
'{"Teste":{"title":"O teu title"}}'
);
$response = $this->client->getResponse();
$this->assertJsonResponse($response, Codes::HTTP_CREATED);
}
控制器:
/**
*
* @Config\Route(
* "/teste/new",
* name="postTestNew"
* )
* @Config\Method({"POST"})
*
* @param Request $request the request object
*
* @return View|Response
*/
public function postNewTeste(Request $request){
return $this->processFormTest($request);
}
/**
* Method for create the process form to Advertisements
*
* @param Request $request
*
* @return mixed
*/
private function processFormTest(Request $request){
$form = $this->createForm(
new TesteType(),
new Teste()
);
$form->bind($request);
//$from->handleRequest($request);
if ($form->isValid()) {
$test = $form->getData();
return $test;
}
return View::create($form, Codes::HTTP_BAD_REQUEST);
}
问题是当我使用handleRequest()时,方法isValid()返回false,因为表单没有提交 . 所以我尝试将handleRequest更改为bind方法 . 在最后一种情况下,方法isValid()返回true,但方法getData()返回null对象 .
我不知道问题是否是下面的类型表类 .
输入表格:
/**
* The constant name to that type
*/
const TYPE_NAME = "Teste";
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options){
parent::buildForm($builder, $options);
$builder->add("title", ValidationType::TEXT);
}
/**
* {@inheritdoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver){
$resolver->setDefaults(
array(
'csrf_protection' => false,
'cascade_validation' => true,
'data_class' => 'oTeuGato\DatabaseBundle\Entity\Teste'
)
);
}
/**
* Returns the name of this type.
*
* @return string The name of this type
*/
public function getName(){
return AdvertisementType::TYPE_NAME;
}
我需要用两种方式POST实体 . 有人为我的问题提出任何问题吗?
谢谢你的耐心!
2 回答
与表单绑定有同样的问题,我发现解决它的唯一方法是将一个空字符串设置为
getName
函数的形式:我建议在绑定数据时使用
handleRequest
方法,因为不推荐使用bind
方法:它看起来更像是一个黑客,但似乎现在是唯一的方式:https://github.com/FriendsOfSymfony/FOSRestBundle/issues/585
我不完全确定,但我认为's because you'重新发送数据:
'Content-Type' => 'application/json'
而不是
'Content-Type' => 'application/x-www-form-urlencoded'
或者至少我认为这就是为什么handleRequest没有做到这一点的原因 .