簡體   English   中英

Sonata Admin configureFormFields使用自定義表單類型

[英]Sonata Admin configureFormFields using custom form types

我有2個實體:

1.問題

/**
 * @ORM\Table()
 * @ORM\Entity
 */
class Question
{
    /**
     * @ORM\Column(type="smallint", nullable=false)
     */
    private $type;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $test_field;

    /**
     * @ORM\OneToMany(targetEntity="Option", mappedBy="question")
     */
    private $options;
}

2.選項

/**
 * @ORM\Table()
 * @ORM\Entity
 */
class Option
{
    /**
     * @ORM\ManyToOne(targetEntity="Question", inversedBy="options")
     * @ORM\JoinColumn(name="question_id", referencedColumnName="id")
     */
    private $question;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $field_for_question_type_x;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $field_for_question_type_y;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $field_for_question_type_z;
}

根據Question類型,需要使用不同的formType,其中僅包含一些Option字段。

例如:

Questiontype = X應該有場形式$field_for_question_type_x

Questiontype = Y應該有表格字段$field_for_question_type_y

等等

我還創建了那些不同的formTypes,所以問題是如何告訴Sonata Admin $formMapper添加此類表單的集合(基於Question實體類型)?

當前看起來像這樣:

protected function configureFormFields(FormMapper $formMapper)
{
    $Question = $this->getSubject();

    $formMapper->add('test_field');

    if ($Question->getId()) {
        $formMapper->with('Options');

        switch ($Question->getType()) {
            case 'X':
                // Here I would need to add collection of \My\Bundle\Form\OptionXType()
                $formMapper->add('options', ????????);
                break;
            case 'Y':
                // Here I would need to add collection of \My\Bundle\Form\OptionYType()
                $formMapper->add('options', ????????);
                break;
        }
    }
}

應該添加什么來提供這種功能?

答案很簡單:

->add('options', 'sonata_type_collection',
    array(),
    array(
        'edit' => 'inline',
        'inline' => 'table',
        'admin_code' => $type_based_admin_code # each has custom form configuration
    )
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM