Symfony 3.4, как передать данные Javascript в контроллер?

Я хочу сохранить объект в базе данных с динамическим содержимым. У меня есть поле ввода, где люди могут писать текст внутри. Я хочу, чтобы содержимое поля ввода было заголовком объекта. Я могу получить содержимое через Javascript и сохранить объект через контроллер. Но я не могу понять, как передать данные из Javascript в контроллер.

Это то, что я пробовал и пробовал:

Javascript:


//Content I need to store
var outputOfInputField = document.getElementById("inputCategory").value;

//Ajax call with JSON that I think I need for pass data to controller.
$.ajax({
   url : '/createcategory',
   type: "POST",
   data: {
      'output': outputOfInputField
   },
   success : function (data) {
      console.log("SUCCES" + data);
   },
   error   : function () {
      console.log("ERROR");
   }
});

Контроллер:

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\User as User;
use Appbundle\Entity\Category as Category;


class HomePageController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */

    public function getData() {
       ...//Not important
    }


    /**
     *  @Route("/create-category", name="newCat")
    */
    public function createObject() {

        //Tried to get the data from JSON file here, dont know what it does and also does not work, gives me an error... Saying i need a use on top of this controller. If I add it it still dont work.

        // $form = $this->get('form.factory')->createBuilder(FormType::class)
        //     ->add('ndf', CollectionType::class, array(
        //         'entry_type' => NoteDeFraisType::class,
        //         'label' => false,
        //         'allow_add' => true,
        //         'allow_delete' => true,
        //     ))
        //     ->getForm();

        //     if ($request->isXMLHttpRequest()) {
        //         $output = $request->request->get('output');
        //         echo $output;
        //         var_dump($output);
        //         print_r($output);
        //     }




        //This is where I create the object and store it in the database.
        $category = $this->getDoctrine()
            ->getRepository('AppBundle:Category')
            ->findall();

        $category = new Category();

        //At the $outputFromJavascript should be the place where my javascript content has to be. Now it does not work, it only works when I put a hardcoded text in it like this "Hello".
        $category->setTitle($outputFromJavascript);

        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($category);
        $em->flush();

        return new Response('Created product id '.$category->getId());
    }
}

Надеюсь, я ясно изложил вопрос :)


person Allart    schedule 21.11.2019    source источник


Ответы (1)


Я сам придумал решение :D. Я не знал, что мне нужен Request в моей функции, и теперь знаю, что он делает.

JavaScript остался прежним, теперь контроллер выглядит так:


<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\User as User;
use Appbundle\Entity\Category as Category;


class HomePageController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */

    public function getData() {
       //...
    }

    /**
     *  @Route("/create-category", name="newCat")
    */
    public function createCategory(Request $request) {
        // dump($request);
        // dump($request->request->get('output'));

        $output = $request->request->get('output');

        $category = $this->getDoctrine()
            ->getRepository('AppBundle:Category')
            ->findall();

        $category = new Category();
        $category->setTitle($output);

        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($category);
        $em->flush();

        return new Response('Created product id '.$category->getId());
    }
}

Что я изменил/добавил:

//Added Request $request
public function createCategory(Request $request) {
//Added line for getting the output of ajax/json post.
$output = $request->request->get('output');
}
person Allart    schedule 22.11.2019