2015-07-07 2 views
0

я разработал коллекцию формы по следующей ссылке:Symfony2 удалить элемент в коллекции

http://symfony.com/doc/current/cookbook/form/form_collections.html

мне удалось добавить новый элемент в моей коллекции, но не может удалить их. Вот мой код:

/** 
* My Controller 
*/ 
public function editAction($id, Request $request) 
{ 
    $em = $this->getDoctrine()->getManager(); 

    $content = $em->getRepository('MyAppBundle:Content')->find($id); 

    if (!$content) { 
     throw $this->createNotFoundException('Unable to find Content entity.'); 
    } 

    $originalEpisodes = new ArrayCollection(); 

    foreach ($content->getEpisodes() as $episode) { 
     $originalEpisodes->add($episode); 
    } 
    $editForm = $this->createEditForm($content , $this->generateUrl('content_update', array('id' => $content ->getId())), 'PUT', 'Update'); 


    if ($editForm->isValid()) { 

     // remove the relationship between the tag and the Task 
     foreach ($originalEpisodes as $episode) { 
      if (false === $content->getEpisodes()->contains($episode)) { 
       // remove the Task from the Tag 
       $episode->getEpisodes()->removeElement($content); 

       // if it was a many-to-one relationship, remove the relationship like this 
       $episode->setContent(null); 

       //$em->persist($episode); 

       // if you wanted to delete the Tag entirely, you can also do that 
       $em->remove($episode); 
      } 
     } 

     $em->persist($content); 
     $em->flush(); 
    } 


    $deleteForm = $this->createDeleteForm($id); 

    return $this->render('BbdBongoAppBundle:Content:edit.html.twig', array(
     'entity'  => $content, 
     'edit_form' => $editForm->createView(), 
     'delete_form' => $deleteForm->createView(), 
     'tabs'  => $this->tabs, 
    )); 
} 

JavaScript Часть

$(document).ready(function() { 
     var items{{ name|capitalize }}Count = {{ form|length }}; 

     $('#add-{{ name }}-{{ id }}').click(function() { 
      {# Get the template to add new value #} 
      var valueList  = $('#edit_{{ name }}-{{ id }}'); 
      var newWidget  = valueList.data('prototype'); 
      newWidget   = newWidget.replace(/__name__/g, items{{ name|capitalize }}Count); 

      items{{ name|capitalize }}Count ++; 

      {# Add a new field and a link to delete #} 
      var newLi = $("<li></li>").append(newWidget); 
      $('#add-{{ name }}-{{ id }}').before(newLi); 
      {% if allow_delete %} 
       addTagFormDeleteLink($(newLi)); 
      {% endif %} 
      return false; 
     }); 

     {# Add a reference to the removal of existing values #} 
     {% if allow_delete %} 
      $('#edit_{{ name }}-{{ id }} > li').not('ul.errors li').each(function() { 
       addTagFormDeleteLink($(this)); 
      }); 
     {% endif %} 
    }); 

    function addTagFormDeleteLink($tagFormLi) { 
     var $removeFormA = $('<a href="#">delete this tag</a>'); 
     $tagFormLi.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 
      $tagFormLi.remove(); 
     }); 
    } 

<ul class="collection" id="edit_{{ name }}-{{ id }}" data-prototype='{{ prototype is defined ? form_widget(prototype)|e('html') : '' }}'> 

Entity:

public function addEpisode(Episode $episode) 
{ 
    $this->episodes->add($episode); 
    $episode->setContent($this); 
    return $this; 
} 

/** 
* Remove episode 
* 
* @param Episode $episode 
* @return $this 
*/ 
public function removeEpisode(Episode $episode) 
{ 
    $this->episodes->removeElement($episode); 
    $episode->getContent($this); 
    return $this; 
} 

/** 
* Get episodes 
* 
* @return Episode[]|\Doctrine\Common\Collections\Collection 
*/ 
public function getEpisodes() 
{ 
    return $this->episodes; 
} 

Я провел более 12 часов, но не могу понять, почему удалить не работает при добавлении работает ?

ответ

0

Используйте $em->flush(); после $em->remove($episode);, когда вы удаляете объект, вы добавляете его в список, который нужно удалить, а не сам. Удаление происходит на flush.

+0

это не работает до сих пор .. любой другой ключ ?? Я правильно следил за документом symfony, но все же не понимаю, в чем причина. в моем содержании у меня много эпизодов, для которых требуется опция удаления –

0

Вы забыли карту запроса в форму с

$editForm->handleRequest($request); 

прямо перед этой линией: if ($editForm->isValid())

Смежные вопросы