Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling controller from twig

Tags:

twig

symfony

I'm currently discovering Symfony, and I have some trouble calling a function from one of my controllers.

> class CsvController extends Controller {

public function generateCsvAction(){
    $conn=$this->get('database_connection')

    $results=$conn->query("
    SELECT *
    FROM external_attribute;
    ")

    $response=new StreamedResponse();
    $response->setCallback(function() use($results)){
        $handle=fopen("/home/basile/Documents/backend/src/CampaignBundle/Controller/test.csv","w+");
        fputcsv($handle,array('test1
            test2,
            test3,
            test4,
            test5,
            test6,
            test7,
            test8')
        ),';');
    }

    fclose($handle);
}

$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition','attachment; filename="test.csv"');      
return $response;  

}

I already set everything in my routing.yml :

export_csv:
defaults: { _controller: CampaignBundle:Controller:CsvController.php }

and now I want to call it from a button in a file named "index.html.twig" . I know we can render from the controller some variables and array, but here i directly want to call a function

If you have any kind of idea, it would be very welcomed !

like image 625
Basile Mauvieux Avatar asked Oct 20 '25 04:10

Basile Mauvieux


1 Answers

To directly call a controller from your template :

{{ render(controller(
    'NameOfYourBundle:NameOfYourClass:NameOfYourFunction'
)) }}

If controller needs parameters (eg) :

{{ render(controller(
    'NameOfYourBundle:NameOfYourClass:NameOfYourFunction', { 'id': 3 }
)) }}
like image 126
Guillaume Harari Avatar answered Oct 21 '25 18:10

Guillaume Harari