具有类型和不同选项的一般实体的 Symfony 形式

Symfony form for a general entity with a type and different options

我是 symfony 的新手,我对它的功能有一些体验。我遇到了一个问题,我将简化它以便更好地理解:假设我们有一个形状学说实体(我只想要一个 table 来存储不同类型的形状):

class Shape {
   protected $id;
   protected $type;
   protected $options;
}

根据形状类型,选项会有所不同:

class Rectangle extends Shape {
    protected $options = array('width' => 20, 'height' => 20);
    protected $type = 'rectangle';
}
class Circle extends Shape {
    protected $options = array('radius' => 15);
    protected $type = 'circle';
}

现在我想用 formBuilder 为 adding/creating 这样的实体创建一个通才表单(我正在使用奏鸣曲,但它不是很重要)

因此,对于类型的选择输入和选项的其他输入将根据所选择的类型而改变。 (我有一个函数 returns 每个扩展 class 上可用选项及其类型的数组

.content {
  font-family: Arial;
}
<form class="content">
  <label>Type : </label><select name="type">
    <option value="circle">Circle</option>
    <option value="rectangle">Rectangle</option>
  </select>

  <fieldset>
    <legend>Circle</legend>
    <input type="number" name="radius" placeholder="Radius">
  </fieldset>
  <fieldset>
    <legend>Rectangle</legend>
    <input type="number" name="width" placeholder="Width">
    <input type="number" name="height" placeholder="Height">
  </fieldset>
</form>

这种方法正确吗?

我该如何实现这种形式? (我的第一个想法是 ajax 或直接输出每个选项的每个输入,然后 javascript 函数将根据选择的类型显示正确的输入)

非常感谢任何 opinion/better 方法。

我通常执行以下步骤:

1.原则继承映射

首先确保您使用 doctrine inheritance mapping approaches 之一作为您的实体,例如'JOINED' table 方法:

# AppBundle/Entity/Shape.php
use Doctrine\ORM\Mapping as ORM;

/**  
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorMap({
 *     "rectangle" : "AppBundle\Entity\Rectangle",
 *     "circle" : "AppBundle\Entity\Circle"
 * })
 */
class Shape {
   protected $id;
   protected $type;
   protected $options;
}

2。在您的管理服务定义中设置子 classes:

# app/config/services.yml
app.admin.shape:
    class: AppBundle\Admin\ShapeAdmin
    arguments: [~, AppBundle\Entity\Shape, SonataAdminBundle:CRUD]
    tags:
        - { name: sonata.admin, manager_type: orm, group: admin, label: InterestService }
    calls:
        - [setSubclasses, [{'Rectangle': AppBundle\Entity\Rectangle, 'Circle': AppBundle\Entity\Circle}]]

3。检查管理员中的对象类型 class

现在您可以在管理员 class 中查看主题类型,并根据自己的喜好操作视图。你可以,例如更改 configureFormFields 方法中的编辑表单:

# AppBundle/Admin/ShapeAdmin.php
protected function configureFormFields(FormMapper $formMapper)

    /** @var Shape $shape */
    $shape = $this->getSubject();

    // add form fields for both types
    $formMapper
        ->add('service', null, ['disabled' => true]);

    // add specific form fields
    if ($shape instanceof Rectangle) {

       // custom rectangle form fields

    } elseif ($shape instanceof Circle {

       // custom circle form fields

    }
}