我是symfony框架的新手。我试图用FOSRestbundle创建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);
}
控制器:
/**
*
* @ConfigRoute(
* "/teste/new",
* name="postTestNew"
* )
* @ConfigMethod({"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' => 'oTeuGatoDatabaseBundleEntityTeste'
)
);
}
/**
* Returns the name of this type.
*
* @return string The name of this type
*/
public function getName(){
return AdvertisementType::TYPE_NAME;
}
我需要通过两种方式对实体进行POST。有人对我的问题有什么建议吗?
谢谢你的耐心!
表单绑定也有同样的问题,我找到的唯一解决方法是为表单getName
函数设置一个空字符串:
/**
* Returns the name of this type.
*
* @return string The name of this type
*/
public function getName(){
return '';
}
我建议在绑定数据时使用handleRequest
方法,因为bind
方法已被弃用:
private function processFormTest(Request $request){
$form = $this->createForm(
new TesteType(),
new Teste()
);
$from->handleRequest($request);
if ($form->isValid()) {
$test = $form->getData();
return $test;
}
return View::create($form, Codes::HTTP_BAD_REQUEST);
}
这看起来更像是一次黑客攻击,但目前看来这是唯一的方法:https://github.com/FriendsOfSymfony/FOSRestBundle/issues/585
我不完全确定,但我认为这是因为您使用:'Content-Type' => 'application/json'
发送数据
代替'Content-Type' => 'application/x-www-form-urlencoded'
或者至少我认为这就是handleRequest没有做它的事情的原因。