在Symfony 2.5中使用ajax设置实体属性(选择一个单选按钮)

时间:2018-04-03 03:16:30

标签: ajax symfony symfony-2.5 jquery-3

我想在我的Symfony项目(Symfony 2.5和jQuery 3)中集成Ajax。我想在选择单选按钮时更新实体的属性。现在,我可以获得我选择的行的id。我已经搜索了如何实现这一点,但我还没有成功。

JS代码

$(document).ready(function(){
    $("input:radio[name=locacion_destacada]").click(function () {
         var id = $(this).parent().parent().attr('dataId');
         alert(id);
         $.ajax({
             url: "/update-destacado",
             type: "POST",
             data: { id : id },
             success: function (response) {
                 alert(response);
             },
             error: function (XMLHttpRequest, textStatus, errorThrown) {
                 alert('Error: ' + errorThrown);
             }
         });

     });
});

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

您可以通过在ajax的网址中调用它来在控制器中执行此操作:

url : {{ path('your_route', {'id': id})}};

并且在控制器功能中,您可以根据需要更新您的实体

答案 1 :(得分:0)

您需要一个控制器操作,由“update-destacado”路由调用。然后从请求中读取ID并更新您的实体。

答案 2 :(得分:0)

我可以解决它。我遵循了page (answer n°8)的想法,同时牢记你的答案。谢谢你的帮助。

控制器代码

public function DestacadoAction(Request $request, $id){

    $em = $this->getDoctrine()->getManager();

    //Encontrar la locacion que ya estaba como destacada y dejarla como destacado=false
    $locacionDestacadaAntigua = $em 
        ->getRepository('FilmsBundle:Locaciones') 
        ->findOneBy(
            array(
                'destacado' => true
            ));

    $locacionDestacadaAntigua->setDestacado(false);
    $em->persist($locacionDestacadaAntigua);
    $em->flush();

    $em = $this->getDoctrine()->getManager();

    //Dejar como destacada la nueva locacion
    $locacionDestacadaNueva = $this->getDoctrine() 
        ->getRepository('FilmsBundle:Locaciones') 
        ->findOneBy(
            array(
                'idLocacion' => $id
            ));
    $locacionDestacadaNueva->setDestacado(true);
    $em->persist($locacionDestacadaNueva);
    $em->flush();

    return new Response("Ha seleccionado la locación \"" . $locacionDestacadaNueva->getNombreLocacion() . "\" como destacada.");
}

JS代码

$(document).ready(function(){
    $(".button").on("click", function (e) {
        $.post(this.href).done(function (response) {
            alert(response);
            location.reload();
        });
    });
});

树枝代码

{% if locacion.destacado == true %}
    <td align="center">
        <a class="button" href="{{ path('admin_destacado_update', { 'id': locacion.idLocacion }) }}">
            <button class="btn btn-default">
                <i class="glyphicon glyphicon-ok"></i>
            </button>
        </a>
    </td>
{% else %}
    <td align="center">
        <a class="button" href="{{ path('admin_destacado_update', { 'id': locacion.idLocacion }) }}">
            <button class="btn btn-sm">
                <i class="glyphicon glyphicon-remove"></i>
            </button>
        </a>
    </td>
{% endif %}