symfony-docs icon indicating copy to clipboard operation
symfony-docs copied to clipboard

[ObjectMapper] More details on transform: in target class

Open tacman opened this issue 5 months ago • 1 comments

The transform examples are all shown on a source class, e.g.

#[Map(target: 'displayPrice', transform: [PriceFormatter::class, 'format'])]
public float $price = 0.0;

https://symfony.com/doc/current/object_mapper.html#transforming-values

If the data is coming from CSV or JSON and does not yet have a class, I'd like to know if it's possible to call a transformer from the target class before the assignment. In particular, I have

{ 
    'price': '$200'
}

And I'd like to transform it to an int without the '$'.

If this is possible, please add an example. If it's not possible, please document that transformers only work from within the source class, not the target class. If that's true, perhaps the #[Map] attribute should throw an error for something like this:

        #[Map(source: 'price'), transform: [self::class, 'cleanupCurrency'])]
        public int $price

tacman avatar Jun 29 '25 10:06 tacman

Maybe that this works using a class transform, pr welcome.

soyuka avatar Jul 24 '25 08:07 soyuka