0

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

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

Try modifying the code as given below. It includes changes to your controller actions as well as the ajax call in the template.

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

//modified code
$status = 'error';
$html = '';
if($medidas){
    $data =$this->render('AtajoBundle:Ajax:medidasYUnidades.html.twig', array('medidas' => $medidas));
    $status = 'success';
    $html = $data->getContent();
}

$jsonArray = array(
    'status' => $status,
    'data' => $html,
);

$response = new Response(json_encode($jsonArray));
$response->headers->set('Content-Type', 'application/json; charset=utf-8');

return $response;

}

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

         //modified code
        $status = 'error';
        $html = '';
        if($unidad){
            $data = $this->render('AtajoBundle:Ajax:unidad.html.twig', array('unidad' => $unidad));

            $status = 'success';
            $html = $data->getContent();
        }

        $jsonArray = array(
            'status' => $status,
            'data' => $html,
        );

        $response = new Response(json_encode($jsonArray));
        $response->headers->set('Content-Type', 'application/json; charset=utf-8');

        return $response;

    }

JavaScript in template:

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

              var parsedData =JSON.parse(result);
                if(parsedData.status ==='success'){
                    userListDiv.html(parsedData.data);
                     $(medidahermano).html(parsedData.data);
                }else{
                    //handle no result case
                }
                     }
                }); 

8 Comments

I tried my previous code without ajax , and works perfectly. The problem is I need to use Ajax. But amazingly I get this error
Are you still getting the same error? Which is the controller action corresponding to que_unidad path?
que_unidad: pattern: /unidad defaults: { _controller: AtajoBundle:Tablas:recuperarUnidad }
If you want and not bother you, you prune to give me your email , to send you files .
The problem with your controller is that it returns html. In my answer, what I am doing is getting the html mark up and then json encoding it and returning inside the response.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.