简体   繁体   中英

Symfony FosRestBundle - form route without format

I am trying to bootstrap simple REST app using latest Symfony (2.4.5) with FOSRestBundle (dev-master 6b384c1).

My configuration:

fos_rest:
    format_listener: true
    view:
        view_response_listener: true

sensio_framework_extra:
    view:    { annotations: false }
    router:  { annotations: true }

My routing:

products:
    type:     rest
    resource: Telemetrik\Bundle\ProductBundle\Controller\ProductsController

Controller:

<?php

// namespace & imports

class ProductsController extends Controller
{
    /**
     * @return Form
     * @View("TelemetrikProductBundle::form.html.twig")
     */
    public function newProductAction()
    {
        return $this->getForm();
    }

    /**
     * @param Request $request
     * @return View|Form
     * @View
     */
    public function postProductsAction(Request $request)
    {
        $form = $this->getForm();

        $form->handleRequest($request);

        if ($form->isValid()) {
            // Logic placeholder
        }

        return $form;
    }

    protected function getForm()
    {
        return $this->createForm(new ProductType());
    }
}

When using router:debug I get:

new_product              GET    ANY    ANY  /products/new.{_format}
post_products            POST   ANY    ANY  /products.{_format}

Which is mostly fine BUT since newProductAction is supposed to be a form:

  • I don't want it to be accessible from formats other than HTML
  • I want to access my form from /products/new not /products/new.html (which right seems to be the only option I can access that resource). If I go to products/new I get: Format '' not supported, handler must be implemented
sensio_framework_extra:
    view:    { annotations: false }
    router:  { annotations: true }

fos_rest:
    routing_loader:
        default_format: json
    format_listener: true
    view:
        view_response_listener: true

me helped add format default to json

fos_rest:
    routing_loader:
        default_format: json

Add this to your config.yml :

fos_rest:
    format_listener:
        rules:
            - { path: ^/products/new, priorities: [html, json, xml], fallback_format: html, prefer_extension: false }

This should set the html extension as the default for this path, and should make it so the extension is not required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM