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



我想在我的Symfony Project(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);
             }
         });
     });
});

任何帮助都非常感谢。

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

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

和控制器函数中您可以按照

来更新实体

您需要一个控制器操作,该操作由您的" update-destacado"路线称为。然后从请求中读取ID并更新您的实体。

我可以解决它。我遵循了此页面的想法(答案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();
        });
    });
});

TWIG代码

{% 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 %}

最新更新