2015-07-21 2 views
0

Я хочу отобразить форму редактирования в Modal Popup с информацией соответствующего ID. Другими словами, я хочу отображать динамические данные из базы данных в модальном всплывающем окне по ссылке.Как динамически отображать данные в Bootstrap Modal Popup в Symfony2

Что я пытался до сих пор: Twig файл, который есть список всех данных:

<table class="table table-striped table-hover table-bordered" style="margin-top:30px;" > 
      <thead> 
      <tr> 
       <th>{{ knp_pagination_sortable(entities, '#', 'a.id') }}</th> 
       <th {% if entities.isSorted('a.name') %} class="sorted"{% endif %}> {{ knp_pagination_sortable(entities, 'Name', 'a.name') }}</th> 
       <th class="hidden-480">Full Address</th> 
       <th>Action</th> 
      </tr> 
      </thead> 
      <tbody> 
      {% set count = '1' %} 
      {% for entity in entities %} 
      <tr> 
       <td>{{ entity.id }}</td> 
       <td>{{ entity.name }}</td> 
       <td>{{ entity.address }}</td> 

       <td> 
        <a href="#" onclick="editDocument();" data-id="{{ entity.id }}" role="button" data-toggle="modal" class="open-editBox" ><button type="button" class="btn blue">Edit</button></a> 
        {#<a href="{{ path('venue_edit', { 'id': entity.id }) }}">Edit</a>#} 
        <a href="#deleteModle" data-id="{{ entity.id }}" role="button" data-toggle="modal"><button type="button" class="btn blue">Delete</button></a> 

       </td> 

       {% set count = count + '1' %} 
       {% endfor %} 
      </tr> 



      </tbody> 
     </table> 

функция JQuery для динамического ID прохода:

function editDocument(){ 
    $(document).on("click", ".open-editBox", function() { 
     var editId = $(this).data('id'); 
     $.ajax({ 
      type: 'GET', 
      url: editId+"/edit", 
      //data: {"editId": editId}, 
      success: function(response){ 
       // alert($.get()); 
       $('#editPlayerModel').html(response); 
      } 
     }); 
     // alert(editId); 
     //$(".modal-body #editId").val(editId); 
    }); 
} 

функции контроллера для редактирования данных и сделать форму:

/** 
* Displays a form to edit an existing Venue entity. 
* 
* @Route("/{id}/edit", name="venue_edit") 
* @Method("GET") 
* @Template() 
*/ 
public function editAction($id) 
{ 
    //print_r($id); exit; 
    $em = $this->getDoctrine()->getManager(); 

    $entity = $em->getRepository('JplAdminFunctionBundle:Venue')->find($id); 

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

    $editForm = $this->createEditForm($entity); 
    $deleteForm = $this->createDeleteForm($id); 

    return array(
     'entity'  => $entity, 
     'edit_form' => $editForm->createView(), 
     'delete_form' => $deleteForm->createView(), 
    ); 
} 

edit.html.twig Файл содержит Редактировать форму (я хочу эту форму для отображения в модальной всплывающих окон):

{{ form(edit_form) }} 

После нажатия на кнопку EDIT, он ничего не отображает даже не какая-либо ошибка

ПРИМЕЧАНИЕ: Я использовал generate:doctrine:crud команда выполнить операции CRUD

Я знаю, что я чувствую себя где-то в потоке или функции jQuery или код контроллера, но не в состоянии определить точный конфликт.

Помощь меня, спасибо

ответ

1
<a href="#" onclick="editDocument();" data-id="{{ entity.id }}" role="button" data-toggle="modal" class="open-editBox" ><button type="button" class="btn blue">Edit</button></a> 

В приведенной выше html структуры у вас есть onclick событие обрабатывается, и если вы видите свою функцию editDocument Js затем:

function editDocument(){ 
    $(document).on("click", ".open-editBox", function() { 
     var editId = $(this).data('id'); 
     $.ajax({ 
      type: 'GET', 
      url: editId+"/edit", 
      //data: {"editId": editId}, 
      success: function(response){ 
       // alert($.get()); 
       $('#editPlayerModel').html(response); 
      } 
     }); 
     // alert(editId); 
     //$(".modal-body #editId").val(editId); 
    }); 
} 

у вас есть $(document).on('click'..., который является ненужным. Я бы предложил использовать любой из вышеперечисленных.Либо удалите onclick от структуры и удалить вашу функцию, обернутые вокруг $(document).on('click'... или вносить изменения в функции, как показано ниже:

<a href="#" onclick="editDocument(this);" data-id="{{ entity.id }}" role="button" class="open-editBox" ><button type="button" class="btn blue">Edit</button></a> 

JS

function editDocument(ctrl){ //pass this ctrl from html 
    var editId = $(ctrl).data('id'); 
    var res="";//store the obtained result 
    var success=false; //open modal only if success=true 
    //url should match your server function so I will assign url as below: 
    var url="/editAction"; //this is the server function you are calling 
    var data=JSON.stringify({"id":editId}); 
    $.when(//To execute some other functionality once ajax call is done 
    $.ajax({ 
     type: 'GET', 
     url: url, 
     dataType:'json',//type of data you are returning from server 
     data: data, //better to pass it with data 
     success: function(response){ 
      res=response; 
      success=true; 
     }, 
     error:function(){ 
      //handle error 
     }, 
    })).then(function(){ 
      if(success) 
      { 
       //assign each values obtained from response which is now 
       //stored in "res" inside modal element by mapping it to 
       //necessary controls in modal 
       $("yourmodalid").modal("show"); //show the modal 
      } 
    }); 
} 

ИЛИ если вы используете $(document).on('click'.... затем изменить его, как показано ниже:

HTML

<a href="#" data-id="{{ entity.id }}" role="button" class="open-editBox" ><button type="button" class="btn blue">Edit</button></a> 

JS

$(document).on("click", ".open-editBox", function() { 
    var editId = $(this).data('id'); //get the id with this 
    var res="";//store the obtained result 
    var success=false; //open modal only if success=true 
    //url should match your server function so I will assign url as below: 
    var url="/editAction"; //this is the server function you are calling 
    var data=JSON.stringify({"id":editId}); 
    $.when(
     $.ajax({ //To execute some other functionality once ajax call is done 
      type: 'GET', 
      url: url, 
      data: data, //better to pass it with data 
      dataType:'json',//type of data you are returning from server 
      success: function(response){ 
       res=response; 
       success=true; 
      }, 
      error:function(){ 
       //handle error 
      }, 
     })).then(function(){ 
       if(success) 
       { 
        //assign each values obtained from response which is now 
        //stored in "res" inside modal element by mapping it to 
        //necessary controls in modal 
        $("yourmodalid").modal("show"); //show the modal 
       } 
    }); 
}); 

Я чувствую, вы кнопку внутри якоря не нужно, и вы можете просто применить классы на якорь себя, чтобы получить кнопку чувство, как показано ниже:

<a href="#" data-id="{{ entity.id }}" role="button" class="open-editBox btn blue">EDIT</a> 

Обратите внимание на это. Дайте мне знать, если вы столкнулись с любыми проблемами.

+0

Спасибо за ваш ответ, я попробовал ваш код выше устранения 'document on click event' в jQuery. Но все же проблема такая же. Я не вижу всплывающее окно – Geetika

+0

, убедитесь, что ваш код поражает серверную функцию! вы получаете значения, возвращаемые функцией 'server'? –

+0

да, я получаю 'editID', я изменил свой URL-адрес следующим образом:' var url = "{{path ('venue_edit')}}; // это серверная функция, которую вы вызываете, ее выполнение этого исключения '(« Некоторые обязательные параметры отсутствуют («id») для создания URL-адреса для маршрута «место_соединения».) ' – Geetika

0

thx. я уже взял эти примеры, модифицировал его, и он работает:

я принял событие JS DoubleClick, чтобы показать модальную

JS:

$(document).on("dblclick", ".opdia", function() { 
     var editId = $(this).data('id'); 
     var res = ""; 
     var success = false; 
     var url = "###route_to_controller###?id=" + editId; 
     $.when(
       $.ajax({ 
       type: 'GET', 
       url: url, 
       success: function(response){ 
        res=response; 
        success=true; 
        }, 
       error:function(){ 
        //handle error 
       }, 
       })).then(function(){ 
         if(success) 
         { 
          $("#myModal").html(res).modal("show"); 
         } 
        }); 
       }); 

я получил Twig шаблона, показывающий все объекты в одной таблице. Я объявил <tr> для управления модальным. HTML:

<tr class="opdia" data-id="{{ entity.id }}" role="button">... 

<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div> 

И мой контроллер:

/** 
* @Route("/SomeUrl", name="###route_to_controller###") 
*/ 
public function getDetailAction(Request $request) 
{ 
    $id = $request->query->get('id'); 

    return $this->render('::YOURTWIGTEMPLATE.html.twig',array('id' => $id)); 
} 

И мой Detail Twig Шаблон:

<div class="modal-dialog"> 
<div class="modal-content"> 
    <div class="modal-header"> 
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> 
    <h4 class="modal-title" id="myModalLabel">Modal title - ID -> {{ id }}</h4> 
    </div> 
    <div class="modal-body"> 


    </div> 
    <div class="modal-footer"> 
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
    <button type="button" class="btn btn-primary">Save changes</button> 
    </div> 
</div> 
</div> 
Смежные вопросы