The Sonata Admin Bundle truly is a jewel of a package that can help you to perform feats of wonder with your admin screens. But there are a few lesser-known tricks that deserve a little more attention than the documentation gives. One such topic is the sonata_type_collection form type. The sonata_type_collection comes in handy when you have a “one-to-many” relationship (i.e. one post may have many tags) and wish to embed the form for tags within the form for posts. Talk about killing two birds with one stone, you can combine any related entities onto the same form and have them all persisted at once. In theory this sounds wonderful, but the devil is in the details. So, without further ado …Компоненты маркетинга
In my example I have a promotion entity with a standard one-to-many bi-directional relationship to promo_rules try this site. I’ve tried this with many-to-many associations, but sonata complains.
Next we go ahead and create Sonata Admin classes for each entity. Here is the PromotionAdmin:
And here is the PromoRuleAdmin:
The trick to notice here is that I actually commented out the “promotion” field relationship here? We want to create an admin for promo_rule that does NOT include the related promotion field. Why? Because we want to be able to specify the promotion in the parent form (the promotion form). Our promo_rule form will be embedded within the promotion form. If you’re still with me, then the next question becomes, how exactly do we attach the promo_rule to the promotion if its omitted from the form?
// in the PromotionAdmin
Yes indeed, the sonata admin class allows for prePersist and preUpdate calls that allows us to set the promotion for the rule before persisting. Of course don’t forget to declare your admin classes as services in your configs. Other than that, I hope that this helps somebody out there.