Symfony 3:使用Ajax调用控制器deleteAction

时间:2017-11-07 12:18:05

标签: php ajax symfony

我正在尝试使用ajax删除Symfony3实体。

问题是$form->isValid()返回false,但表单(或任何子元素)上没有错误。我在这里缺少什么?

控制器

/**
 * @Route("/{profileID}/delete", name="profile_delete")
 * @ParamConverter("Profile", options={"mapping": {"profileID": "id"}})
 * @Method("DELETE")
 */
public function deleteAction(Request $request, Profile $Profile)
{
    $form = $this->createDeleteForm($Profile);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->remove($Profile);
        $em->flush();

        return new JsonResponse(array('message' => 'profile removed'));
    } else {
        return new JsonResponse(array('message' => 'error'));
    }
}

private function createDeleteForm(Profile $Profile)
{
    return $this->createFormBuilder()
        ->setAction($this->generateUrl('profile_delete', array('profileID' => $Profile->getId())))
        ->setMethod('DELETE')
        ->getForm()
    ;
}

枝条

$.ajax({
  url: "{{ path('profile_delete', {'profileID': Profile.id}) }}",
  type: 'delete',
  success:function(data){
    console.log(data);
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
    console.log(textStatus);
    console.log(errorThrown);
  }
});

1 个答案:

答案 0 :(得分:1)

您在没有csrf-token的情况下提交表单。快速解决方法是将令牌添加为数据:

$.ajax({
    url: "{{ path('profile_delete', {'profileID': Profile.id}) }}",
    type: 'delete',
    data: {
        form: {
            _token: "{{ csrf_token('form') }}"
        }
    },
    success:function(data){
        console.log(data);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.log(textStatus);
        console.log(errorThrown);
    }
});

form这里是表单名称,也可以手动设置。例如。 delete-form

private function createDeleteForm(Profile $Profile)
{
    return $this
        ->get('form.factory')
        ->createNamedBuilder('delete-form', FormType::class, null, [
            'action' => $this->generateUrl('profile_delete', array('profileID' => $Profile->getId())),
            'method' => 'DELETE',
        ])
        ->getForm()
    ;
}

使用:

$.ajax({
    url: "{{ path('profile_delete', {'profileID': Profile.id}) }}",
    type: 'delete',
    data: {
        'delete-form': {
            _token: "{{ csrf_token('delete-form') }}"
        }
    },
    success:function(data){
        console.log(data);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.log(textStatus);
        console.log(errorThrown);
    }
});