recipe_dynamic_form_modification.rst 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. Modifying form fields dynamically depending on edited object
  2. ============================================================
  3. It is a quite common situation when you need to modify your form's fields because
  4. of edited object's properties or structure. Let us assume you only want to display
  5. an admin form field for new objects and you do not want it to be shown for those
  6. objects that have already been saved to the database and now are being edited.
  7. This is a way for you to accomplish this.
  8. In your ``Admin`` class' ``configureFormFields`` method you are able to get the
  9. current object by calling ``$this->getSubject()``. The value returned will be your
  10. linked model. Then, you should be able to dynamically add needed fields to the form:
  11. .. code-block:: php
  12. use Sonata\AdminBundle\Admin\Admin;
  13. use Sonata\AdminBundle\Form\FormMapper;
  14. class MyModelAdmin extends Admin
  15. {
  16. // ...
  17. protected function configureFormFields(FormMapper $formMapper)
  18. {
  19. // Description field will always be added to the form:
  20. $formMapper->add('description', 'textarea');
  21. $subject = $this->getSubject();
  22. if ($subject->isNew()) {
  23. // The thumbnail field will only be added when the edited item is created
  24. $formMapper->add('thumbnail', 'file');
  25. }
  26. }
  27. }