8

长话短说:使用 FOSRestBundle 我正在尝试通过 POST 调用创建一些实体,或通过 PUT 修改现有实体。

这里的代码:

/**
 * Put action
 * @var Request $request
 * @var integer $id Id of the entity
 * @return View|array
 */
public function putCountriesAction(Request $request, $id)
{
    $entity = $this->getEntity($id);
    $form = $this->createForm(new CountriesType(), $entity, array('method' => 'PUT'));
    $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,
    );
} //[PUT] /countries/{id}

如果我调用 /countries/{id} 并使用 PUT 传递像 {"description":"Japan"} 这样的 json,它会使用 id=1 修改我的国家/地区,并放置一个空描述。

相反,如果我尝试使用此方法创建一个新实体:

/**
 * Create new Countries (in batch)
 * @param  Request $request json request
 * @return array           redirect to get_coutry, will show the newly created entities
 */
public function postCountriesAction(Request $request)
{
    $entity = new Countries();
    $form = $this->createForm(new CountriesType(), $entity);
    $form->bind($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirectView(
            $this->generateUrl(
                'get_country',
                array('id' => $entity->getId())
            ),
            Codes::HTTP_CREATED
        );
    }

    return array(
        'form' => $form,
    );
} //[PUT {"description":"a_description"}] /countries

它给了我一个错误说:

exception occurred while executing 'INSERT INTO countries (description) VALUES (?)' with params [null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'description' cannot be null

所以似乎我无法正确传递绑定到表单的请求。

请注意,如果我按照此处的建议对请求进行 json_decode,它会回复

{
    "code":400,
    "message":"Validation Failed",
    "errors":{
        "errors":[
            "This value is not valid."
        ],
        "children":{
            "description":[
            ]
        }
    }
}

有什么建议吗?

谢谢,劳斯

4

2 回答 2

21

我解决了:)

这就是它以前不起作用的原因:

在我的表单定义中,名称是“zanzibar_backendbundle_countries”。

public function getName()
{
    return 'zanzibar_backendbundle_countries';
}

因此,要将请求绑定到此表单,json 应该如下所示:

{"zanzibar_backendbundle_countries": [{"description": "Japan"}]}

因为我希望它像

{"id":1,"description":"Italy"}

我不得不从表格中删除名称:

public function getName()
{
    return '';
}

一般来说,如果你想发布一个带有占位符的 json

"something":{"key":"value"}

您的表单名称必须完全是“某物”

于 2013-12-14T15:14:33.213 回答
0

尝试这个 :

if ($form->isValid()) {
    $entity = $form->getData();       //   <------ you didn't bind entity to the form
    $em = $this->getDoctrine()->getManager();
    $em->persist($entity);
    $em->flush();
于 2013-12-13T14:08:31.543 回答