Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FOSRestBundle doesn't work in Symfony 4.1

I have problem with returning views with FOSRestBundle working under Symfony 4.1 Project.

This is code from my controller:

class NewsController extends FOSRestController
{

    public function getNewsAction()
    {
        $data = ['news1', 'news2'];

        $view = $this->view($data, 200);

        return $this->handleView($view);
     }
}

fos_rest.yaml

fos_rest:
    param_fetcher_listener:  true
    allowed_methods_listener:  true
    routing_loader: true
    view:
        view_response_listener:  'force'
    format_listener:
        rules:
            - { path: ^/api, prefer_extension: true, fallback_format: json, priorities: [ json, html ] }

framework.yaml

framework:
    secret: '%env(APP_SECRET)%'
    php_errors:
        log: true

sensio_framework_extra:
    view:        { annotations: true }

So I have pretty basic configuration, and I am still getting errors like this:

(1/1) RuntimeException You must enable the SensioFrameworkExtraBundle view annotations to use the ViewResponseListener.

I tried to remove "view: view_response_listener: 'force'", but then I am having this error:

An instance of Symfony\Bundle\FrameworkBundle\Templating\EngineInterface >must be injected in FOS\RestBundle\View\ViewHandler to render templates.

I'am struggling with it for hours. Is it because of Symfony 4 beta status? Or maybe I am doing something wrong? Maybe I miss some dependecies? I couldn't find anything helpful about this problem in official documentation.

like image 327
jankes83 Avatar asked Nov 27 '17 13:11

jankes83


3 Answers

Do you send the Accept: application/json in your request?

If not, you do not necessarily need twig, but you need to remove html from the format configuration in the bundle config:

fos_rest:
    format_listener:
        rules:
            - { path: ^/, prefer_extension: true, fallback_format: json, priorities: [ json ] }

The default is to have html in the priorities, and that requires twig.

like image 132
magnetik Avatar answered Nov 17 '22 13:11

magnetik


Add line to config/packages/framework.yaml

framework:
    templating: { engines: ['twig'] }

it will solve

An instance of Symfony\Bundle\FrameworkBundle\Templating\EngineInterface >must be injected in FOS\RestBundle\View\ViewHandler to render templates.

like image 32
Alexander Matrosov Avatar answered Nov 17 '22 14:11

Alexander Matrosov


You must enable the SensioFrameworkExtraBundle view annotations

sensio_framework_extra:
    view:        { annotations: false }
like image 2
Alister Bulman Avatar answered Nov 17 '22 13:11

Alister Bulman