0

Our Symfny application allows to print labels on a sheet with 6 labels. The user can specify an additional text for each label and whether to print it or not.

At the moment HTTP GET parameters contain the configuration:

labels[0][enabled]=true
labels[0][text]=foo
labels[1][enabled]=false
labels[1][text]=bar
...

In our controller the enabled field would be interpreted as string, but I'd like to to pass booleans to the view template.

$request->query->get('labels')[0]['enabled']
// 'true'

There is $request->query->getBoolean('...'), but I cannot use it here, because the booleans are nested in the array.

I could convert the entries manually in a foreach loop, but I'm looking for a better solution.

I thought that Symfony Forms would be useful here, but I don't want to create form type classes for such cases. Fortunately forms can be created inline like this:

$this->createFormBuilder($data)
    ->add(...)
    ->getForm()

In my case however I'd need to use CollectionType. The inner form type (with enabled and text fields) has to be defined as class name / string.

So I wonder if there is way to create an inline form as above with nested data?

If not, is there a another way to parse such request data? We have other similar cases in our application where other developers just manually parsed data from GET parameters which is always problematic with non-strings types like booleans or dates.

fishbone
  • 3,140
  • 2
  • 37
  • 50
  • `$request->get('labels')` should return an array that you can work on – john Smith Sep 08 '22 at 08:23
  • there is no unified pattern to recognize such booleans, the parameter value could be `1 || 0` or `on || off` etc. in any way it will be a string – john Smith Sep 08 '22 at 08:26
  • 1
    You should probably check the docs page on [how to embed a collection of forms](https://symfony.com/doc/current/form/form_collections.html). Each of your entries contains a label and/or enabled flag (and possibly more fields). You could have an object that encapsulates both (similar to tags in the example in the docs) and then have a form where you have a collection of them. edit: You can inline this as well, but that would mean inlining a form in an inline form and I can’t imagine that’s easy to set up – dbrumann Sep 10 '22 at 06:40
  • @johnSmith There is a pattern (e.g. https://www.php.net/manual/de/filter.filters.validate.php) and Symfony Froms support it as well. BTW `filter_input_array` would be an interesting solution, but also doesn't seem to support nesting. – fishbone Sep 12 '22 at 08:21
  • @dbrumann I know embedded collections. The point of my question is how to do this without classes (i.e. "inline") – fishbone Sep 12 '22 at 08:23
  • @fishbone +1 thanks for that referrence – john Smith Sep 12 '22 at 09:23

0 Answers0