Rvanlaak
Rvanlaak

Reputation: 3085

Data Transformer on multiple fields and parent entity

I've been searching for a while, but was not able to find specific documentation on my DataTransformer use-case. Ofcourse there is the Symfony2 cookbook chapter, but it does not resolve my specific use-case. I could only find info on transforming a single field.

Entities

I've got two entities (with a 0..n relationship)

Order

  1. priceTotal (other fields aren't relevant)

OrderLine

  1. amount
  2. priceFactor
  3. pricePerPiece
  4. priceTotal

Use-case

I do not want to calculate the Order->priceTotal on the fly in the view every time. That is why I'd like to create a transformer on the OrderLine that recalculates a couple of values on submit:

  1. The Order->priceTotal should be a sum of all OrderLine->priceTotal
  2. The OrderLine->priceTotal should be (amount * priceFactor * pricePerPiece)

Since I don't want to put this logic in every Controller function, I assume the DataTransformer is correct solution (?). Is the FormType the correct level for this type of validation?

Upvotes: 4

Views: 2027

Answers (1)

Dragony
Dragony

Reputation: 1722

I don't think a DataTransformer is what you're looking for. A DataTransformer can mutate the submitted content for one field in your form, but does not have access to any fields around it. This is probably something you'll want to do with LifeCycleCallbacks.

http://docs.doctrine-project.org/en/2.0.x/reference/annotations-reference.html#annref-haslifecyclecallbacks

Here is an example of how LifeCycleCallbacks are used:

http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html

It does not reflect what you want to do, but it will teach you what LifeCycleCallbacks are and how to use them.

Upvotes: 3

Related Questions