Working on a new project as I always do with Symfony, a constant deprecation notice showed up when working with forms:
User Deprecated: Since symfony/http-foundation 5.1: Retrieving a non-string value from "Symfony\Component\HttpFoundation\InputBag::get()" is deprecated, and will throw a "Symfony\Component\HttpFoundation\Exception\BadRequestException" exception in Symfony 6.0, use "Symfony\Component\HttpFoundation\InputBag::all($key)" instead.
This deprecation notice can be easily removed from your code and it will be explained in this article.
How to trigger this deprecation notice
Consider the following example that uses a basic GET form without a FormType in order to explain you easily. The form looks like this:
<form action="http://sandbox/index" method="get">
<label>
Option 1
<input type="checkbox" name="my_form[options][]" value="1">
</label>
<label>
Option 2
<input type="checkbox" name="my_form[options][]" value="2">
</label>
</form>
And when it's submitted, the following index action in the controller will handle the request:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
class PagesController extends AbstractController
{
public function index(Request $request): Response
{
// 1. Use the get method to retrieve a non-string parameter, for example the
// As a GET form, the URL may look like:
// http://sandbox/index?my_form%5Boptions%5D%5B%5D=1&my_form%5Boptions%5D%5B%5D=2
$data = $request->query->get("my_form");
// data will contain an array indeed:
// [
// "options" => [1, 2]
// ]
// The previous code will trigger the deprecation notice although it works
return $this->render('pages/index.html.twig', [
]);
}
}
The solution to this issue is quite easy though.
Solution
The deprecation itself is not caused because you use the $request->query->get
or $request->request->get
methods, but to use them to retrieve values that are interpreted as arrays. For example, if someone opens the following URL of your project (http://sandbox/page?age=23) and you try to obtain the age parameter with the mentioned methods like this:
// 23
echo $request->query->get("age");
That won't throw the exception! Because the parameter itself is a string or number. However, if the request contains the array format (http://sandbox/page?my_form%5Boptions%5D%5B%5D=1&my_form%5Boptions%5D%5B%5D=2), to prevent the deprecation notice from appearing, you will need to obtain the value, in this case, my_form
using the all
method and providing the key as first argument:
$request->query->all("my_form");
// data will contain an array indeed without the deprecation notice:
// [
// "options" => [1, 2]
// ]
If the given key doesn't exist, the method will return an empty array.
Happy coding ❤️!