Sonata Admin - Custom AJAX call

蓝咒 提交于 2019-12-14 03:14:05

问题


I have created a custom list view in sonata admin to display a calendar.

I'm trying to add events to the calendar dynamically, but I'm getting an error with the CSRF token being invalid.

I have the following code:

public function listAction()
{
    if (false === $this->admin->isGranted('LIST')) {
        throw new AccessDeniedException();
    }

    $datagrid = $this->admin->getDatagrid();
    $formView = $datagrid->getForm()->createView();

    // set the theme for the current Admin Form
    $this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());

    $em = $this->getDoctrine()->getManager();
    $events = $em->getRepository('BMCrmBundle:Event')->findAll();

    $event = new Event();

    $formEvent = $this->createForm(new EventType(), $event );

    return $this->render($this->admin->getTemplate('list'), array(
        'action'     => 'list',
        'form'       => $formView,
        'datagrid'   => $datagrid,
        'csrf_token' => $this->getCsrfToken('sonata.batch'),
        'events'     => $events,
        'formEvent'  => $formEvent->createView()
    ));
}

view

var url = "{{ path('create_event', { _sonata_admin: 'bm.crm.admin.event'} ) }}";
$.post(url, form.serialize(), function(data) {
   alert(data);
});

This always returns that the CSRF token is invalid

Any ideas?


回答1:


Check if in your view, you have the following line:

{{ form_rest(form) }}

because I believe that you are rendering form fields one by one and not the whole form at once and forgot to render the rest of the form, which contains the CSRF token.



来源:https://stackoverflow.com/questions/19492795/sonata-admin-custom-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!