4

これが私たちのコントローラーです:

function getLocationsAction(Request $request) {

        $dm = $this->get('doctrine.odm.mongodb.document_manager');
        $query = $dm->createQueryBuilder('MainClassifiedBundle:Location')->select('name', 'state', 'country', 'coordinates');
        $locations = $query->getQuery()->execute();

        $data = array(
            'success' => true,
            'locations' => $locations,
            'displaymessage' => $locations->count() . " Locations Found"
        );

        $view = View::create()->setStatusCode(200)->setData($data);
        return $this->get('fos_rest.view_handler')->handle($view);
    }

fosrestbundle の config.yml は次のとおりです。

fos_rest:
    view:
        formats:
            json: true
        templating_formats:
            html: true
        force_redirects:
            html: true
        failed_validation: HTTP_BAD_REQUEST
        default_engine: twig

ルートは次のとおりです。

MainClassifiedBundle_get_locations:
    pattern:  /locations/
    defaults: { _controller: MainClassifiedBundle:ClassifiedCrudWebService:getLocations, _format:json}
    requirements:
        _method:  GET

text/html を取得するのはなぜですか? 応答を application/json にする方法を教えてください。

これは現在大きな苦痛を引き起こしているので助けてください

4

2 に答える 2

12

ビューを静的に作成しており、リスナーを有効にしていません。

この方法では、フォーマットの推測は必要ありません。

形式を引数として関数に渡し、View オブジェクトに形式を設定します。

function getLocationsAction(Request $request, $_format) {
{
    // ...
    $view = View::create()
         ->setStatusCode(200)
         ->setData($data)
         ->setFormat($_format)   // <- format here
    ;
    return $this->get('fos_rest.view_handler')->handle($view);
}

ドキュメントの章The View Layerを参照してください。


自動フォーマット推測が必要な場合は、リスナーを有効にする必要があります。

fos_rest:
    param_fetcher_listener: true
    body_listener: true
    format_listener: true
    view:
        view_response_listener: 'force'

詳細については、「リスナー サポート」の章を参照してください。

于 2013-07-05T07:57:54.227 に答える