Forms setMappedType with typed properties in 7.4

dkorpar
Member | 132
+
+1
-

This feature has an issue with php 7.4.
Let's say we have form with input type hidden and this is mapped to integer property in class
something like this

$form->addHidden('count');
$form->setMappedType(FormType::class);


class FormTyp
{
    public int $count;
}

currently this will allways throw an error

TypeError

Typed property FormType::$count must be int, string used, since value from hidden is allways string.
In the end in HTML this allways ends up as string and when setting value you also allways have to provide string, but feels kinda needed to have this solved and get data mapped correctly…

Possible solutions I see:

1. setMappedType checks type if it has typed properties and cast values to it
Looks like easiset solution for developer using it, little bit of reflection and if type is simple shouldn't really be a problem, maybe with containers and more complex types could get a bit tricky (not really thought it through completelly)

2. setMappedTypeFactory method where developer will implement mapping it's own
Simplest possible implementation, but not that straightforward for developer although he then gets full control.
Developer could also probably use existing hydration packages. This implementation sounds to me like most convienant, it's super easy to implement and will satisfy everyone needs

Ofcours one can allways getValues as array and do mapping on it's own, but if it's provided in library its more likely more developers will use it and use better practices.

Last edited by dkorpar (2020-05-08 16:42)

Matúš Matula
Member | 257
+
0
-

Hi @dkorpar you can force the type by adding rule INTEGER on the hidden input like

$form->addHidden('count')
	->addRule($form::INTEGER);

and it will cast automatically

dkorpar
Member | 132
+
0
-

Hey, thanks for reply. I would like to avoid that and have model for form which is automatically hydrated to it. Maybe even connect it somehow would be awesome.