faisal nasir
faisal nasir

Reputation: 165

Call custom function of controller from ajax symfony2

I've created the forms using Sonata Admin Bundle. Then I've created my own Controller (TestController) and override the CRUD controller,

I've added a new function in the TestController,

namespace IFI2\MainProjectBundle\Controller;

use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Bridge\Monolog\Logger;
use Sonata\AdminBundle\Controller\CRUDController as Controller;


//use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class TestController extends Controller
{

    public function getProductPricesAction() {

         file_put_contents("/Applications/XAMPP/htdocs/IFI2 CMS/Logs.txt","HELO",FILE_APPEND);

          return new Response(json_encode($response)); 

    }
}

Then I'm trying to access this function via my javascript Code,

<script type="text/javascript">

    function test1() {

        $.ajax({
            type:"POST",
            //dataType: "json",
            url: '{{ path('main_project.admin.test')}}',
            success: function(successMsg) {
                alert("successMsg");

            },
            error: function(errorMsg) {
                alert("errorMsg");

            }
        });
     }

</script>

Here's my routing.yml,

main_project.admin.test:
  pattern:  /getProductPrices/
  defaults: { _controller: IFI2MainProjectBundle:Test:getProductPrices}

I've already had services.yml entry for this entity,

main_project.admin.cobrand:
    class: MainProjectBundle\Admin\TestAdmin
    arguments: [~, MainProjectBundle\Entity\Test, "MainProjectBundle:Test"]
    tags:
        - {name: sonata.admin, manager_type: orm, group: admin, label: Test}
    calls:
        - [setTemplate, [edit, MainProjectBundle:Test:edit.html.twig]]

I'm getting the following error in my response,

There is no _sonata_admin defined for the controller MainProjectBundle\Controller\TestController and the current route main_project.admin.test

Kindly, help me how to embed it ?

Thanks, Faisal Nasir

Upvotes: 3

Views: 1906

Answers (2)

Shadi Akil
Shadi Akil

Reputation: 383

In routing.yml add the following:

main_project.admin.test:
  pattern:  /getProductPrices/
  defaults: { _controller: IFI2MainProjectBundle:Test:getProductPrices,"_sonata_admin": "main_project.admin.cobrand" }

Upvotes: 0

Petr Slavicek
Petr Slavicek

Reputation: 456

Add new route in your Admin method configureRoutes

protected function configureRoutes(RouteCollection $collection)
{
    parent::configureRoutes($collection);
    $collection->add('get_product_prices');
}

Remove your route main_project.admin.test

New route has $baseRouteName from your admin as prefix and has name:

base_route_name_get_product_prices

using

{{ path('base_route_name_get_product_prices') }}
//or with admin
{{ admin.generateUrl('get_product_prices') }}

Upvotes: 3

Related Questions