Created
March 27, 2016 17:26
-
-
Save webdevilopers/2a4fc620c10ba8390bf4 to your computer and use it in GitHub Desktop.
How to use optional ParamConverter with null default in Route in Symfony Controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Sps\Bundle\CalculationBundle\Controller; | |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; | |
class CalculationController extends Controller | |
{ | |
/** | |
* @Route("/calculation/dormer/calculate/{priceQuoteId}", defaults={"priceQuoteId" = null}) | |
* @ParamConverter("priceQuoteRequest", isOptional="true", class="SpsPriceQuoteBundle:PriceQuoteRequest", options={"id" = "priceQuoteId"}) | |
* @Template() | |
* @Security("has_role('ROLE_DOMO_CALCULATION_DORMER')") | |
*/ | |
public function createAction(PriceQuoteRequest $priceQuoteRequest = null) | |
{ | |
} | |
} |
👍
I can't see any benefit in this argument.
try this defaults={"priceQuoteId" = ""}
Thanks @mssimi!
In that case I will get an empty string but since type hints I would prefer null
since I have to convert a string into a value object afterwards:
class DefaultController extends Controller
{
public function calculateAction(?string $priceRequestId = null)
{
if (null !== $priceRequestId) {
$id = PriceRequestId::fromString($priceRequestId);
}
}
in php7.2 and symfony 4.3 its as simple as
class CalculationController extends Controller
{
/**
* @Route("/calculation/dormer/calculate/{priceQuoteId}")
* @ParamConverter("priceQuoteRequest", class="SpsPriceQuoteBundle:PriceQuoteRequest", options={"id" = "priceQuoteId"})
* @Template()
* @Security("has_role('ROLE_DOMO_CALCULATION_DORMER')")
*/
public function createAction(?PriceQuoteRequest $priceQuoteRequest)
{
}
no defaults in Route, no isOptional="true", no = null in function definition. Simply ?PriceQuoteRequest
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
defaults
in@Route
throws: No route found for "GET /calculation/dormer/calculate".= null
on type hint throws: Unable to guess how to get a Doctrine instance from the request information.isOptional
on@ParamConverter
no error.At the bottom line 1 and 2 are required to handle null. But 3 doesn't change anything.
What is the actual purpose of
isOptional
then? Isn't mentioned in the cookbook:Possibly related:
Twitter discussion:
https://twitter.com/webdevilopers/status/714143790005620736