Search code examples
phpajaxvalidationsymfony4

symfony4.3 can't use ValidatorInterface in controller when using ajax


I'm trying to validate a form submitted with ajax in my controller using the ValidatorInterface.

But I get this error:

Could not resolve argument $validator of "App\SocialStudio\AdminBundle\Controller\InfluencersController::addinfluencerajax()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?

This is my controller:

<?php
namespace App\SocialStudio\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\Influencer;
use App\Form\Type\InfluencerType;

use Symfony\Component\Validator\Validator\ValidatorInterface;

class InfluencersController extends AbstractController
{
    public function Influencers(Request $request)
    {   
        // Get all Inlfuencers
        $influencers = $this->getDoctrine()
            ->getRepository(Influencer::class)
            ->findAll();

        // create modal form
        $influencer = new Influencer();
        $addInfluencerForm = $this->createForm(InfluencerType::class, $influencer);

        return $this->render('@Admin/influencers.html.twig', [
            'menu' => 'influencers',
            'influencers' => $influencers,
            'addInfluencerForm' => $addInfluencerForm->createView(),
        ]);

    }

    public function addInfluencerAjax(Request $request, ValidatorInterface $validator)
    {   

        ... form handling happens in this function ...

    }

}

This is my code for the ajax call:

$('#submitAddInfluencerForm').click(function(e){
           e.preventDefault();
            addInfluencerForm = $('#addInfluencerForm').serialize();

            $.ajax({
                url:'{{ path('AddInfluencerAjax') }}',
                type: "GET",
                dataType: "json",
                data: {
                    "influencer": addInfluencerForm
                },
                async: true,
                success: function (return_data)
                {
                    ...
                }
            });

        });

services.yaml

services:
  _defaults:
    autowire: true
    autoconfigure: true

  App\:
    resource: '../src/*'
    exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

  App\Controller\:
    resource: '../src/Controller'
    tags: ['controller.service_arguments']

and I put this in my framework.yaml

framework:
  validation: { enable_annotations: true }

Solution

  • Wtih the help of Leprechaun I found a way that works.

    Add to controller class:

    private $validator;
        public function __construct(
            ValidatorInterface $validator
        ) {
            $this->validator = $validator;
        }
    

    and get the validator in the function like this:

    $validator = $this->validator;