简体   繁体   中英

Using an embedded form in Symfony2

I'm having a problem with embedding forms in Symfony2. I could be doing something technically wrong, but maybe the mistake I've made is on the level of the db-setup and embedding a form is not necessary in the first place. Let's first focus on that, before I present the code.

I have made two entities: V and O. They both represent locations, but refer to different types of locations. Through ref-id's, they each refer to an entity Address. Multiple V's could refer to the same address, multiple O's could refer to the same address, and there could even be a V and an O on the same address. Displaying V's, O's and Addresses works (the controllers and the routing work). Creating or editing Addresses also works fine; I've made a form type called AddressType and this renders and works fine too.

V and O also have formTypes: VType and OType. They have their Twig templates, routes, controller actions, etc. in place.

Now I want users to be able to enter a new V in a form, where there are also fields available to enter a new Address. So I don't want users to pick an already existing address from a list of some kind (however I got that working), but I want them to be able to add a new address. Should the address already exist in the db table "Addresses" (which is very well possible), Symfony2 should refer to that existing address instead of creating the same one again.

Now my problem is, that I don't succeed in presenting the Address form (AddressType) embedded in the V or O forms. Basically I want the AddressType form to be rendered as part of a V or an O form. Is this possible?

However, it could very well be that my db-setup is not okay and I should not have made Address a separate entity (and db table), but I should have made it part of the entities V and O. That would also solve the issue I guess, but is it good practice?

I appreciate your help in advance.

I had similar issue. This is complicated form that may not be so easy to be done. The best way is to make a custom form type OR even a raw form (which I'd prefer), and to write controller action that processes this form for you using the Request class directly. Then you can validate your inputs using ConstraintCollections and compose your entities directly using your classes and Doctrine's EntityManager.

This link may get useful - or at least helped me a lot about validation of non-objects: http://www.ricardclau.com/2011/11/how-to-use-symfony2-validator-component-without-forms-entities-and-data-arrays/

So basically you will have to write code here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM