簡體   English   中英

在symfony2中嵌入表單集合

[英]Embed a Collection of Forms in symfony2

大家好,我是symfony2的新手,我正在嘗試做一個簡單的應用程序!

我有3個實體,分別為“ CarInquerito”,“ CarPergunta”和“ CarResposta”,它們之間是相關的,如下面的“有趣”代碼所示。 所有這些屬性都有適當的獲取/設置。

我假裝的是,當我從CarInquerito創建表單時,我將CarPergunta的表單以及CarResposta的表單嵌入到該CarPergunta表單中。 我已經完成了將CarResposta的集合嵌入到CarPergunta表單中的工作,但是當我嘗試將其結果嵌入到CarInquerito中時,似乎不起作用。

class CarInquerito
{
     /**
     * @ORM\OneToMany(targetEntity="CarPergunta", mappedBy="idInquerito", cascade={"persist"})
     */
    private $perguntas;
}

class CarInqueritoType{
    $builder->add('perguntas', 'collection', array(
            'type' => new CarPerguntaType(),
            'allow_add' => true,
            'by_reference' => false,
            'prototype' => true,
            'allow_delete' => true,
            ));
}


class CarInquerito
{
 /**
     * @var CarInquerito
     *
     * @ORM\ManyToOne(targetEntity="CarInquerito", inversedBy="perguntas")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_inquerito", referencedColumnName="id", onUpdate="cascade", onDelete="cascade", nullable = false)
     * })
     */
    private $idInquerito;

  /**
     * @ORM\OneToMany(targetEntity="CarResposta", mappedBy="idPergunta", cascade={"persist"})
     */
    private $respostas;
}

class CarPerguntaType{
   $builder->add('respostas', 'collection', array(
            'type' => new CarRespostaType(),
            'allow_add' => true,
            'by_reference' => false,
            'prototype' => true,
            'allow_delete' => true,
            ));
}

class CarResposta{
   /**
     * @var CarPergunta
     *
     * @ORM\ManyToOne(targetEntity="CarPergunta", inversedBy="respostas")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_pergunta", referencedColumnName="id", onUpdate="cascade", onDelete="cascade", nullable = false)
     * })
     */
    private $idPergunta;
}


class CarRespostaType{
  $builder->add('resposta', 'text');
}

現在控制器:

public function newAction() {

        $CarInquerito = new CarInquerito();
        $form = $this->createForm(new CarInqueritoType(), $CarInquerito);

        return $this->render('CareAdminBundle:CarInquerito:new.html.twig', array(
                    'form' => $form->createView(),
                ));
    }

現在查看:new.html.twig:

<div class="inqueritos">
<div class="perguntas-list">
<ul class="perguntas" data-prototype="{% filter escape %}{% include 'CareAdminBundle:CarInquerito:prototypePergunta.html.twig' with {'form': form.perguntas.get('prototype')} %}{% endfilter %}">
        {% for pergunta in form.perguntas %}
            <li>
            {{ form_widget(pergunta.pergunta) }} 
            </li>
        {% endfor %}

       </ul>
</div>
</div>

--- protoypePergunta.html.twig ----------

<div class="respostas-list" style="background-color: red; padding: 10px;">
    <ul class="respostas" data-prototype="{{ form_widget(form.respostas.get('prototype')) | e }}">
       {% for resposta in form.respostas %}
        <li>{{ form_widget(resposta.resposta) }}</li>
     {% endfor %}

    </ul>
</div>

我有一個javascript文件,在其中添加和刪除鏈接以添加“ Pergunta”和“ Respostas”,如下所示:

$(document).ready(function(){    

    var collectionHolderPerguntas = $('ul.perguntas');

    collectionHolderPerguntas.find('li').each(function() {
        addPerguntaFormDeleteLink($(this));
    });

    // setup an "add a tag" link
    var $addPerguntaLink = $('<a href="#" class="add_pergunta_link">Adicionar pergunta</a>');
    var $newLinkLi = $('<li></li>').append($addPerguntaLink);

      // add the "add a tag" anchor and li to the tags ul
    collectionHolderPerguntas.append($newLinkLi);

    $addPerguntaLink.on('click', function(e) {
        // prevent the link from creating a "#" on the URL
        e.preventDefault();

        // add a new tag form (see next code block)
        addPerguntaForm(collectionHolderPerguntas, $newLinkLi);
    });

    var collectionHolderRespostas = $('ul.respostas');
    collectionHolderRespostas.find('li').each(function() {
        alert("OL");
        addRespostaFormDeleteLink($(this));
    });

    // setup an "add a tag" link
    var $addRespostaLink = $('<a href="#" class="add_resposta_link">Adicionar resposta</a>');
    var $newLinkLiResposta = $('<li></li>').append($addRespostaLink);

    // add the "add a tag" anchor and li to the tags ul
    collectionHolderRespostas.append($newLinkLiResposta);

    $addRespostaLink.on('click', function(e) {
        // prevent the link from creating a "#" on the URL
        e.preventDefault();

        // add a new tag form (see next code block)
        addRespostaForm(collectionHolderRespostas, $newLinkLiResposta);
    });


});

function addPerguntaForm(collectionHolderPerguntas, $newLinkLi) {
    // Get the data-prototype we explained earlier
    var prototype = collectionHolderPerguntas.attr('data-prototype');

    // Replace '$$name$$' in the prototype's HTML to
    // instead be a number based on the current collection's length.
    var newForm = prototype.replace(/\$\$name\$\$/g, collectionHolderPerguntas.children().length);

    // Display the form in the page in an li, before the "Add a tag" link li
    var $newFormLi = $('<li></li>').append(newForm);
    $newLinkLi.before($newFormLi);

     // add a delete link to the new form
    addPerguntaFormDeleteLink($newFormLi);
}

function addPerguntaFormDeleteLink($perguntaFormLi) {
    var $removeFormA = $('<a href="#">apagar</a>');
    $perguntaFormLi.append($removeFormA);

    $removeFormA.on('click', function(e) {
        // prevent the link from creating a "#" on the URL
        e.preventDefault();

        // remove the li for the tag form
        $perguntaFormLi.remove();
    });
}

function addRespostaForm(collectionHolderRespostas, $newLinkLiResposta) {

    // Get the data-prototype we explained earlier
    var prototype = collectionHolderRespostas.attr('data-prototype');
    // 
    // Replace '$$name$$' in the prototype's HTML to
    // instead be a number based on the current collection's length.
    var newFormResposta = prototype.replace(/\$\$name\$\$/g, collectionHolderRespostas.children().length);

    // Display the form in the page in an li, before the "Add a tag" link li
    var $newFormLiResposta = $('<li></li>').append(newFormResposta);
    $newLinkLiResposta.before($newFormLiResposta);

    // add a delete link to the new form
    addRespostaFormDeleteLink($newFormLiResposta);
}

function addRespostaFormDeleteLink($respostaFormLi) {
    var $removeFormA = $('<a href="#">apagar</a>');
    $respostaFormLi.append($removeFormA);

    $removeFormA.on('click', function(e) {
        // prevent the link from creating a "#" on the URL
        e.preventDefault();

        // remove the li for the tag form
        $respostaFormLi.remove();
    });
}

有什么建議嗎? 我一整天都在搜索,我嘗試了很多事情,但沒有找到解決方案。

任何幫助表示贊賞!

謝謝

您需要在newAction()中的對象“ CarInquerito”中放入一些數據。 表單收集食譜中的示例:

$tag1 = new Tag();
        $tag1->name = 'tag1';
        $task->getTags()->add($tag1);
        $tag2 = new Tag();
        $tag2->name = 'tag2';
        $task->getTags()->add($tag2);
        // end dummy code

        $form = $this->createForm(new TaskType(), $task);

如果不這樣做,則不會創建嵌入的表單。

暫無
暫無

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

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