我是新的symfony框架。我試圖用FOSRest bundle創建webservices,但是當我試圖用json實現一個實體的POST方法時遇到了問題。FOSRest Symfony POST使用json
測試:
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更改爲綁定方法。在最後一種情況下,方法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;
}
我需要用兩種方式張貼實體。任何人爲我的問題獲得任何東西?
感謝您的耐心等待!
Ohhh很好......我沒有看到這個問題。今天我試試你的解決方案,表單使用表單工廠。謝謝 ;) – Nbento 2015-03-03 15:24:45