2018-05-20 08:30
浏览 96

PHP symfony 4 ajax表单提交

I'm trying to submit a form using ajax and send it's data to the database, but I don't understand how to proces the data received from the ajax call.

I wrote the following code:

{% extends 'base.html.twig' %}

{% block title %}Assignments | CRM Fabriek{% endblock %}

{% block body %}

    <div class="container">
        <div class="columns">
            <div class="column is-full">
                <div class="level">
                    <h1 class="level-left title title-no-margin is-vcentered">Assignments</h1>

                    <div class="level-right">
                        {% include 'search.html.twig' %}

                        <a href="{{ path("newAssignment") }}" class="level-item button is-success">Add new</a>
                <table class="table is-fullwidth">
                    {% if assignments != null %}
                        {% for assignment in assignments %}
                                <td>{{ assignment.name }}</td>
                                <td>{{ assignment.description }}</td>
                                <td>{{ assignment.status }}</td>
                                    <a class="button is-info is-small" href="{{ path('overviewAssignment', {'id': assignment.id}) }}"><i class="fa fa-eye"></i></a>
                                    <a class="button is-warning is-small" href="{{ path('editAssignment', {'id': assignment.id}) }}"><i class="fa fa-pencil"></i></a>
                                    <button class="button is-success is-small" onclick="openModal({{ assignment.id }})"><i class="fa fa-plus"></i></button>
                        {% endfor %}
                    {% else %}
                            <td colspan="4">No entries</td>
                    {% endif %}
                <div class="pagerfanta">
                    {{ pagerfanta(pager)}}
                    <div class="modal">
                        <div class="modal-background"></div>
                        <div class="modal-card">
                            <header class="modal-card-head">
                                <p class="modal-card-title">Modal title</p>
                            <section class="modal-card-body">
                                {{ form_start(form, {'attr': {'id': 'task_form'}}) }}
                                {{ form_row(form.name, {'attr': {'class': 'input'}}) }}
                                {{ form_row(form.description, {'attr': {'class': 'textarea'}}) }}

                                {{ form_label(form.status) }}
                                <div class="control">
                                    <div class="select">
                                        {{ form_widget(form.status) }}

                                {{ form_end(form) }}
                            <footer class="modal-card-foot">
                                <button id="submit_task" class="button is-success">Save changes</button>
                                <button class="button" onclick="closeModal()">Cancel</button>

{% endblock %}

{% block javascripts %}
        function openModal(id){
            $('#submit_task').attr('onClick', 'submitTask('+ id +');');

        function closeModal(){

        function submitTask(id){

            form = $('#task_form').serialize();

                url:'{{ path('submit_task') }}',
                type: "POST",
                dataType: "json",
                data: {
                    "task": form
                async: true,
                success: function (return_data)
                error: function (xhr, ajaxOptions, thrownError)

{% endblock %}

With the following method in the controller:

     * @Route("/", name="submit_task")
    public function add_task(Request $request){
        $form_data = $request->get('task');

        return new JsonResponse($form_data);

The form is created in the index action:

     * @Security("is_authenticated()")
     * @Route("/assignments", name="assignments")
    public function index(Request $request)

        $assignment_rep = $this->getDoctrine()->getRepository(Assignment::class);

        if($request->get('search') == null) {
                $assignments = $assignment_rep->findAll();
                /* @var User $user */
                $user = $this->getUser();
                $assignments = array();
                foreach($user->getAssignments() as $assignment){
                    array_push($assignments, $assignment);

                $assignments = $assignment_rep->search($request->get('search'));
                /* @var User $user */
                $assignments = $assignment_rep->searchUser($request->get('search'), $this->getUser()->getId());

        $page = $request->query->get('page', 1);

        $adapter = new ArrayAdapter($assignments);

        $pagerfanta = new Pagerfanta($adapter);

        $task = new Task();
        $form = $this->createForm(TaskFormType::class, $task);

        $assignments = $pagerfanta->getCurrentPageResults();

        return $this->render('assignment/index.html.twig', array(
            'assignments' => $assignments,
            'pager' => $pagerfanta,
            'form' => $form->createView()

I would like to know how to process the form data without the "form" object in the function. Could anyone help me out with this problem!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douzhi9921 2018-05-20 08:47

    Your problem is something I stumbled upon back in Symfony3 and since then I've been trying various methods in handling content sent via AJAX.

    Get AJAX data

    This part is simple, in the controller simply call $data = $request->getContent();

    Create a service

    Create a service to help handle this kind of data. It uses Symfony's validator (see constructor: ValidatorInterface), and has a method called validateAndCreate that takes in as a parameter $data (which is the AJAX request body content) and $entityClassName (which is the entity to create and populate with data, example: User::class will generate the class name string)

    Normalizer, Encoder and Serializer

    These three will be important in handling your AJAX content. $data can be deserialized and injected directly into an entity instance (created from the ClassName parameter)

    If data is sent as JSON then use the JsonEncoder, once the serializer object is created then it'll be able to deserialize the JSON data directly into the newly instantiated object (the className in parameter is used to generate the object).

    Once the object is generated, use the validator to check and see if it's a valid object. I recommend to use the @Assert in all Entity objects for the validator to work accordingly.

    class ApiService
        private $validator;
        public function __construct(ValidatorInterface $validator)
            $this->validator = $validator;
        public function validateAndCreate($data, $entityClassName){
            $objectNormalizer = new ObjectNormalizer();
            $normalizers = [$objectNormalizer];
            $encoders = [new JsonEncoder()];
            $serializer = new Serializer($normalizers, $encoders);
            $result = $serializer->deserialize($data, $entityClassName, 'json');
            $errors = $this->validator->validate($result);
            if(count($errors) > 0){
                throw new CustomApiException(Response::HTTP_BAD_REQUEST, (string) $errors);
            return $result;

    Example in use in a controller for creating a new meeting

    public function newMeeting(Request $request, ApiService $apiService, FractalService $fractalService){
            /** @var Admin $admin */
            $admin = $this->getUser();
            /** @var UserRepository $rep */
            $em = $this->getDoctrine()->getManager();
            $data = $request->getContent();
            if(empty($data)) throw new CustomApiException(Response::HTTP_BAD_REQUEST, "Data sent null.");
            /** @var Meeting $test */
            $meeting = $apiService->validateAndCreate($data, Meeting::class);
            //Return data however you wish, I use a FractalService
            $data = $fractalService->generateData($meeting, MeetingTransformer::class, 'meeting');
            return $fractalService->generateResponse($data);

    Client side example of form handling for AJAX

    $("#form").on("submit", function(e){
       let data = {};
          data[object.name] = object.value;
       //TODO: ajax call here with data
       //If ajax call fails because server can't decode
       //Think of doing : data = JSON.stringify(data);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="form">
      <input type="text" value="john" name="firstname"/>
      <input type="text" value="smith" name="lastname"/>
      <input type="text" value="florida" name="address"/>
      <input type="text" value="1234512345" name="phonenumber"/>
      <input type="text" value="john.smith@gmail.com" name="email"/>
      <input type="submit" value="submit this"/>

    打赏 评论

相关推荐 更多相似问题