我正在使用 Symfony 2.2 和最新版本的 FOSRestBundle。因此,我设法使大多数操作起作用,但我似乎对 FormBuilder 有问题,我正在传递我的 PUT 调用的请求。
我已经检查了请求对象,它应该来自我的 Backbone.je 模型(.save())但是在绑定到表单后,实体返回的只有 id,这导致 flush() 因为必填字段而引发错误没有填写。
控制器中的操作:
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS ');
header('Allow GET, POST, PUT, DELETE, OPTIONS ');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type, *');
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Routing\ClassResourceInterface;
use FOS\Rest\Util\Codes;
use Symfony\Component\HttpFoundation\Request;
use Greenthumbed\ApiBundle\Entity\Container;
use Greenthumbed\ApiBundle\Form\ContainerType;
class ContainerController extends FOSRestController implements ClassResourceInterface
{
/**
* Put action
* @var Request $request
* @var integer $id Id of the entity
* @return View|array
*/
public function putAction(Request $request, $id)
{
$entity = $this->getEntity($id);
$form = $this->createForm(new ContainerType(), $entity);
$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,
);
}
/**
* Get entity instance
* @var integer $id Id of the entity
* @return Container
*/
protected function getEntity($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('GreenthumbedApiBundle:Container')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Container entity');
}
return $entity;
}
被调用的表格:
namespace Greenthumbed\ApiBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ContainerType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('description')
->add('isVisible')
->add('type')
->add('size')
->add('creationDate')
->add('userId')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Greenthumbed\ApiBundle\Entity\Container',
'csrf_protection' => false,
));
}
public function getName()
{
return 'greenthumbed_apibundle_containertype';
}
}
到目前为止,我已经尝试了所有方法,但我对 Symfony 还很陌生,我不明白为什么 $entity 不包含请求收到的值。
仅供参考:我已经尝试手动执行此操作,例如使用请求的 ID 实例化一个 Container 类,并使用 setter 向其中输入值,它工作得很好,我只想按照 Symfony 建议的正确方式做事做完了。
非常感谢您提前。