drzfz9995 2015-08-31 00:19
浏览 64
已采纳

返回Ajax - 错误 - Symfony2

For over a week I can not solve a problem with ajax . I have a form where the customer chooses the product to buy , the amount you are going to buy , and to what extent ( 1kg, 5kg, etc ) . Everything works properly, when you choose the product, the other two fields with the corresponding quantities and units will auto . When sending the form, tells me the following error:

The controller must return a response (null given). Did you forget to add a return statement somewhere in your controller?

I'll put all code , but actually the problem should be in the driver. To that reading is not so difficult to do , I will be commenting on each step.

1°: First, sending the form to the view. (obviously , first passes through the routing, but do not go if)

TablasController.php

public function pedidoAction()
    {
        $em = $this->getDoctrine()->getManager();

        $prodped= new ProdPedido();//creo la entidad de los productos
        $form = $this->createForm(new ProdPedidoType(), $prodped);
        $nombres = $em->getRepository('ProyectoAdminBundle:Catalogo')->findByArticulo();


        return $this->render('AtajoBundle:General:pedido.html.twig', array('form' => $form->createView(), 'nombres' => $nombres));

    }

2°: I reduced a little code so that not so long . Here , I present the form, and make the corresponding javascript that handles dynamically add fields , and that I mentioned above, the auto-complete fields. Although this does not go much to the case , since the problem would be in the controller.

pedido.html.twig

{% block content %}

  <section class="pedido">



<form id="formulario" action="{{ path('crear_pedido', { 'id': app.user.id } ) }}" method="post" {{ form_enctype(form) }}>
{{ form_start (form) }}
{{ form_errors(form) }}

    <div id="agrega">
    <ul>
        <li>{{ form_label(form.producto, 'Nombre del producto: ') }}</li>
        <li>{{ form_label(form.cantidad, 'Cantidad que va a llevar: ') }}</li>
        <li>{{ form_label(form.valor, 'Valor en numero (KGS/LTS): ') }}</li>

    </ul>

    <ul class="ul_0">
        <li>{{ form_widget(form.producto, { 'attr': {'class': 'producto_0'} }) }}</li>
        <li>{{ form_widget(form.cantidad, { 'attr': {'class': 'cantidad_0'} }) }}</li>
        <li>{{ form_widget(form.valor, { 'attr': {'class': 'medida_0'} }) }}</li>

    </ul>

    </div>



<div ><input id="agregarCampo" type="button" value="Agregar Producto"/></div>
<div ><input id="quitarCampo" type="button" value="Quitar Producto"/></div>
<div ><input id="enviar" type="submit" id="submit"/></div>

{{ form_end (form) }}

 </section>
{% endblock %}

{% block javascripts %}
    {{ parent() }}
    <script type="text/javascript" src=" {{ asset('bundles/MICARPETA/js/jquery-2.1.4.min.js') }} "></script>
    <script type="text/javascript">
    $(document).ready(function() {

    var loqueagrego;

    var busqueda = $('#busqueda');
    var contenedor       = $("#agrega"); //ID del contenedor
    var AddButton       = $("#agregarCampo"); //ID del Botón Agregar
    var QuitButton = $("#quitarCampo");
    var productos = '{% for nombre in nombres %}<option value="{{ nombre.articulo }}"> {{ nombre.articulo }} </option>{% endfor %}';
    var x = 1;

    //agregar boton
    $(AddButton).click(function (e) {
          //el html que voy a agregar
           loqueagrego = '<ul>';
           loqueagrego = loqueagrego + '<li><label>Nombre del producto: </label></li>';
           loqueagrego = loqueagrego + '<li><label>Cantidad que va a llevar: </label></li>';
           loqueagrego = loqueagrego + '<li><label>Valor en numero (KGS/LTS): </label></li>';
           loqueagrego = loqueagrego + '</ul>';

           loqueagrego = loqueagrego + '<ul class="ul_'+x+'">';
           loqueagrego = loqueagrego + '<li><select class="producto_0" name="producto[]">'+ productos +'</select></li>';
           loqueagrego = loqueagrego + '<li><select class="cantidad_0" name="cantidad[]"></select></li>';
           loqueagrego = loqueagrego + '<li><select class="medida_0" name="medida[]"></select></li>';
           loqueagrego = loqueagrego + '</ul>';
           //lo agrego
           $(contenedor).append(loqueagrego);
           x++; //sumo la cantidad de campos que hay

        return false;
    });


    //quitar boton
    $(QuitButton).click(function (e){
       if (x !== 1){ // si es distinto a 1, remuevo los input que no deseo
       $("#agrega ul:last-child").remove();
       $("#agrega ul:last-child").remove();
       x--;
       }
       return false; 
    });

    //le digo que todos los que se agreguen dinamicamente tambien van a ser afectados
    $('#agrega').on("change",".producto_0", function(e){ 
    var elegido = $(this).val();
    var medidahermano = $(this).parent().parent().attr("class");
    var cantidadhermano = medidahermano;
    medidahermano = $('.'+ medidahermano +' li:last-child');//recupero el ultimo hijo
    medidahermano = medidahermano.children(1); //recupero el primer hijo
    cantidadhermano = $('.'+ cantidadhermano +' li:nth-child(2)');
    cantidadhermano = cantidadhermano.children(1);


      var solido;
      var liquido;
      solido = '<option value="1">1</option>';
      solido = solido + '<option value="5">5</option>';
      solido = solido + '<option value="10">10</option>';
      solido = solido + '<option value="15">15</option>';
      solido = solido + '<option value="20">20</option>';
      solido = solido + '<option value="30">30</option>';
      solido = solido + '<option value="50">50</option>';
      solido = solido + '<option value="100">100</option>';
      liquido = '<option value="6">6</option>'
      liquido = liquido + '<option value="12">12</option>';
      liquido = liquido + '<option value="24">24</option>';
      liquido = liquido + '<option value="48">48</option>';
      liquido = liquido + '<option value="12">96</option>';

    $.ajax({

                          type: "POST",
                          url: "{{ path('que_unidad') }}",
                          data: { 'id' : ' ' + elegido + ' ' },
                          error: function(){
                                alert("Error petición Ajax");
                          },
                          success: function(data){    
                                alert(data);                                               
                                if(data == 'KG' | data == 'unidad'){
                                  $(cantidadhermano).html(solido);
                                }


                                else if(data == 'LTS'){
                                  $(cantidadhermano).html(liquido); 
                                }   

                                $.ajax({
                                          type: "POST",
                                          url: "{{ path('medidas_y_unidades') }}",
                                          data: { 'id' : ' ' + elegido + ' ' },
                                          error: function(){
                                                alert("Error petición ajax");
                                          },
                                          success: function(data){                                                    

                                                $(medidahermano).html(data);

                                          }
                                }); 

                          }

  }); 

     });

});





</script> 

{% endblock %}

3°: This is where it is assumed that this error. For me it is the way to return the information to the ajax , but not really , because it seems like it's okay . Return information through a view, everything works fine , the fields will auto . But sending the form , I get this error.

TablasController.php

public function recuperarMedidasyUnidadesAction(){
        $id = $_POST['id'];
        $em = $this->getDoctrine()->getManager();

        // busco las diferentes unidades que existen (1kg, 5kg, 10kg, etc)
        $medidas = $em->getRepository('ProyectoAdminBundle:Unidades')->findByUnidadesJoinCatalogo($id);

        return $this->render('AtajoBundle:Ajax:medidasYUnidades.html.twig', array('medidas' => $medidas));

    }

    public function recuperarUnidadAction(){
        $id = $_POST['id'];
        $em = $this->getDoctrine()->getManager();

        // busco las diferentes unidades que existen (1kg, 5kg, 10kg, etc)
        $unidad = $em->getRepository('ProyectoAdminBundle:Categoria')->findByUnidad($id);

        return $this->render('AtajoBundle:Ajax:unidad.html.twig', array('unidad' => $unidad));

    }

4°:views

medidasYUnidades.html.twig

{% for medida in medidas  %}

<option value="{{ medida.medida }}">{{ medida.medida }}</option>

{% endfor %}

unidad.html.twig

{{ unidad.unidad }}
  • 写回答

2条回答 默认 最新

  • dpxw17759 2015-08-31 00:56
    关注

    a response object requires data in an associative array. Your code gives an entity object. You have to convert that entity to an array.

    If you would like to convert all the entity data into an array then you could use JMSSerializer. See also this other stackoverflow topic

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页