recipe_dynamic_form_modification.rst 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. And another method ``isCurrentRoute`` for check the current request's route.
  11. Then, you should be able to dynamically add needed fields to the form:
  12. .. code-block:: php
  13. <?php
  14. // src/AppBundle/Admin/PostAdmin
  15. namespace AppBundle\Admin;
  16. use Sonata\AdminBundle\Admin\Admin;
  17. use Sonata\AdminBundle\Form\FormMapper;
  18. class PostAdmin extends Admin
  19. {
  20. // ...
  21. protected function configureFormFields(FormMapper $formMapper)
  22. {
  23. // Description field will always be added to the form:
  24. $formMapper
  25. ->add('description', 'textarea')
  26. ;
  27. $subject = $this->getSubject();
  28. if ($subject->isNew()) {
  29. // The thumbnail field will only be added when the edited item is created
  30. $formMapper->add('thumbnail', 'file');
  31. }
  32. // Name field will be added only when create an item
  33. if ($this->isCurrentRoute('create')) {
  34. $formMapper->add('name', 'text');
  35. }
  36. }
  37. }