Geetika
Geetika

Reputation: 820

How to display data dynamically in Bootstrap Modal Popup in Symfony2

I want to display an edit form in Modal Popup with the information of respective ID. In other words i want to display the dynamic data from the database in modal popup on the link click.

What i have tried so far: Twig file which have list of all the data:

<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 function for the dynamic ID pass:

 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 );
    });
}

Controller function to edit the data and render the form:

   /**
 * 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 file contains the Edit Form (I want this form to display in the modal popup):

{{ form(edit_form) }}

After clicking on the EDIT button, it displays nothing not even any error

NOTE: I have used generate:doctrine:crud command to do the CRUD operations

I know i am lagging somewhere in the flow or the jQuery function or the controller Code, but not able to identifying the exact conflict.

Help me out, thanx

Upvotes: 0

Views: 9655

Answers (2)

FuggyD
FuggyD

Reputation: 19

thx. i've took these examples, modified it and it works:

i took the JS DoubleClick event to show the modal

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"); 
                       }
                    });
                });

I got a Twig Template showing all entities in one table. I declared the <tr> for controlling the modal. 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>

And my Controller:

/**
 * @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));
}

And my Detail Twig Template:

<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>

Upvotes: 0

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

<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>

In the above html structure you have onclick event handled and if you see your editDocument js function then:

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 );
    });
}

you have $(document).on('click'... which is unnecessary. I would suggest to use any one of the above. Either remove onclick from structure and remove your function wrapped around $(document).on('click'... or make changes to your function as below:

<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
           }
    });
}

OR if you are using $(document).on('click'.... then change it as below:

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
               }
    });
});

I feel you don't need button inside anchor and you can just apply classes to anchor itself to get button feeling as below:

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

Have a eye on this. Let me know if you face any issues

Upvotes: 1

Related Questions