In my application I've got a couple of form fields with many options. The problem I experienced is similar to this question: getting and parsing all options at every page load is expensive (Twig renders all options over and over again while no client side caching possible). That problem made me create a way to send the options via AJAX to the browser. Fairly simple approach:
- Get all options (key-value) via AJAX (for example by getting /countries.json) and cache if possible. (in this case it's not very likely country names change very often)
- Use selectize, select2 or a similar plugin to insert the options into the DOM.
- Enjoy a faster Form :-)
To prevent Symfony from querying all options (not necessary: they're loading via AJAX) I added setMaxResults(0)
to the QueryBuilder
when the form is loaded (by adding an option via the controller). Yes, that's kludge. When submitting a form it will still perform a query, because it has to verify if the selected option exists (and check for Constraints).
I would like to create a custom Form Field Type that adds this functionality to the current EntityType
: don't load the options while rendering the form, but still check if the selected option exists. I found many examples related to dynamically modifying a form, but I haven't found examples related to modifying just one form field, independently of it's parent form.
How do I create a form field type like this? What's a good starting point? Extend EntityType
, ChoiceType
or an other approach?
I'm already using Symfony 3.1, so using lazy loading of form choices (New in Symfony 3.2) won't be a problem. Not sure if this new feature is related to my problem.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…