我是 symfony 框架的新手。我正在尝试使用 FOSRest bundle 创建 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);
}
Controller :
/**
*
* @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() 返回空对象。
我不知道问题是否出在下面的类型表单类上。
输入表格:
/**
* 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;
}
我需要用两种方式发布实体。有人对我的问题提出任何建议吗?
感谢您的耐心等待!
最佳答案
表单绑定(bind)也有同样的问题,我发现解决这个问题的唯一方法是为表单 getName
函数设置一个空字符串:
/**
* Returns the name of this type.
*
* @return string The name of this type
*/
public function getName(){
return '';
}
我建议在绑定(bind)数据时使用 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
关于json - 使用 json 的 FOSRest Symfony POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28829538/