簡體   English   中英

如何從Symfony2中的PUT請求獲取參數?

[英]How do I get parameters from a PUT request in Symfony2?

我正在使用Symfony 2.3,我有一個看起來像這樣的方法:

public function addAction() {

    $user = new User();
    $form = $this->createForm(new UserType(), $user);
    $form->handleRequest($this->getRequest());

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

        try {
            return $this
                    ->render(
                            'SomeBundle:Default:adduser.html.twig',
                            array('id' => $user->getId()));
        } catch (Exception $e) {
            throw new HttpException(500, "Error persisting");
        }
    }

    throw new HttpException(400, "Invalid request");
}

這條路線:

some_bundle_adduserpage:
pattern: /user
defaults: { _controller: SomeBundle:User:add }
methods: [POST]

它工作得很好。 我也有這個方法:

public function editAction($id) {

    $response = new Response();

    if (!$this->doesUserExist($id)) {
        $response->setStatusCode(400);
        return $response;
    }

    $user = new User();
    $form = $this->createForm(new UserType(), $user);
    $form->handleRequest($this->getRequest());

    if (!$form->isValid()) {
        $response->setStatusCode(400);
        return $response;
    }

    $user->setId($id);
    $em = $this->getDoctrine()->getManager();

    try {
        $em->persist($user);
        $em->flush();

        $response->setStatusCode(200);
    } catch (Exception $e) {
        $response->setStatusCode(500);
    }

    return $response;
}

這條路線:

some_bundle_edituserpage:
pattern: /user/{id}
defaults: { _controller: SomeBundle:User:edit }
methods: [PUT]
requirements:
    id: \d+

它不起作用。 我可以通過精心設計了一些要求和POST它只是罰款,但PUT不起作用。 具體來說,看起來我沒有在$this->getRequest()獲得任何參數。 為什么$this->getRequest()似乎適用於POST ,但不適用於PUT 我究竟做錯了什么?

這樣就可以了:

$form = $this ->createForm(new UserType(), $user, array('method' => 'PUT'));

method位丟失了。 顯然,Symfony還不夠酷,無法為您獲取參數。 創建表單時,您必須手動告訴它正在處理的請求類型。 雖然這有效,但我不確定這是最好的答案。 我非常願意聽別人的意見。

PUT方法直接流入stdin因此要訪問它,你應該使用php://inputfopen with read

$put = fopen("php://input", "r");

免責聲明在Symfony中可能有一個內置的方法,但我已經忘記了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM