浏览代码

Added recipe for dynamic admin form modification

Stepan Anchugov 11 年之前
父节点
当前提交
8de77909e9
共有 2 个文件被更改,包括 33 次插入0 次删除
  1. 32 0
      Resources/doc/cookbook/recipe_dynamic_form_modification.rst
  2. 1 0
      Resources/doc/index.rst

+ 32 - 0
Resources/doc/cookbook/recipe_dynamic_form_modification.rst

@@ -0,0 +1,32 @@
+Modifying form fields dynamically depending on edited object
+============================================================
+
+It's a quite common situation when you need to modify your form's fields because of edited object's properties or structure. Let's assume you only want to display an admin form field for new objects and you don't want it to be shown for those objects that have alerady been saved to the database and now are being edited.
+
+This is a way for you to accomplish this. 
+
+In your ``Admin`` class's ``configureFormFields`` method you're able to get the current object by calling ``$this->getSubject()``. The value returned will be your linked model. Then, you should be able to dynamically add needed fields to the form:
+
+.. code-block:: php
+    
+    use Sonata\AdminBundle\Admin\Admin;
+    use Sonata\AdminBundle\Form\FormMapper;
+
+    class MyModelAdmin extends Admin {
+    // ...
+
+      protected function configureFormFields(FormMapper $formMapper)
+      {
+        // Description field will always be added to the form:
+        $formMapper->add('description', 'textarea');
+
+        $subject = $this->getSubject();
+
+        // $subject is your underlying model,
+        // do what you need to figure out if you'll have to modify the form
+        if ($subject->isNew()) {
+            $formMapper->add('thumbnail', 'file');
+        }
+      }
+    }
+

+ 1 - 0
Resources/doc/index.rst

@@ -58,3 +58,4 @@ Cookbook
    cookbook/recipe_image_previews
    cookbook/recipe_image_previews
    cookbook/recipe_row_templates
    cookbook/recipe_row_templates
    cookbook/recipe_sortable_listing
    cookbook/recipe_sortable_listing
+   cookbook/recipe_dynamic_form_modification