Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8642115
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T11:41:44+00:00 2026-06-12T11:41:44+00:00

I can’t found a documentation about how to generate a link with the CSRF

  • 0

I can’t found a documentation about how to generate a link with the CSRF token, like in Symfony 1.4:

link_to(__('Delete'), url_for('ntw-delete', $network), array('confirm' => 'Are you sure?', 'method' => 'delete'))

UPDATED: I created a twig extension for that. Maybe it will help to someone

src/UmbrellaWeb/Bundle/ExtraTwigBundle/Twig/LinkExtension.php

<?php
namespace UmbrellaWeb\Bundle\ExtraTwigBundle\Twig;

use Twig_Extension;
use Twig_Function_Method;
use Twig_Environment;
use Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderInterface;

class LinkExtension extends Twig_Extension
{
    protected $csrfProvider;

    public function __construct(CsrfProviderInterface $csrfProvider)
    {
        $this->csrfProvider = $csrfProvider;
    }

    public function getFunctions()
    {
        return array(
            'link_to' => new Twig_Function_Method($this, 'linkToFunction', array(
                'is_safe' => array('html')
            ))
        );
    }

    /**
     * Build a link with anchor
     * 
     * @param string $path
     * @param string $title
     * @param array $options Available options: 
     *  string 'confirm' - Text for the popup
     *  string 'method' - HTTP Method: post, delete, put
     *  string 'csrfIntention' - CSRF intention. If empty then no CSRF. Not used for GET requests
     *  string 'csrfField' - CSRF field name. _token by default
     *  bool 'escape' - escape title, TRUE by default
     */
    public function linkToFunction($path,$title,array $options = array())
    {
        $default = array(
            'csrf_intention' => '',
            'csrf_field' => '_token',
            'escape' => TRUE
        );

        $options = array_merge($default,$options);

        $ecape = $options['escape'];
        unset($options['escape']);

        $return = '<a href="%s"%s>%s</a>';

        $return = sprintf($return,
            htmlspecialchars($path),
            $this->_tagOptions($this->_options2javascript($options)),
            ($ecape)?htmlspecialchars($title):$title
        );

        return $return;
    }

    function _options2javascript($options)
    {
        // confirm
        $confirm = isset($options['confirm']) ? $options['confirm'] : '';

        unset($options['confirm']);

        // method
        $method = isset($options['method']) ? $options['method'] : false;

        unset($options['method']);

        // CSRF Intention
        $csrfIntention = isset($options['csrf_intention']) ? $options['csrf_intention'] : false;

        unset($options['csrf_intention']);

        // CSRF field name
        $csrfField = isset($options['csrf_field']) ? $options['csrf_field'] : false;

        unset($options['csrf_field']);

        $onclick = isset($options['onclick']) ? $options['onclick'] : '';

        if ($confirm && $method)
        {
            $options['onclick'] = $onclick . 'if (' . $this->_confirmJsFunction($confirm) . ') { ' . $this->_methodJsFunction($method,$csrfIntention,$csrfField) . ' };return false;';
        } else 
            if ($confirm)
            {
                if ($onclick)
                {
                    $options['onclick'] = 'if (' . $this->_confirmJsFunction($confirm) . ') { return ' . $onclick . '} else return false;';
                } else
                {
                    $options['onclick'] = 'return ' . $this->_confirmJsFunction($confirm) . ';';
                }
            } else 
                if ($method)
                {
                    $options['onclick'] = $onclick . $this->_methodJsFunction($method,$csrfIntention,$csrfField) . 'return false;';
                }

        return $options;
    }

    function _confirmJsFunction($confirm)
    {
      return "confirm('".$this->_escapeJs($confirm)."')";
    }

    /**
     * Escape carrier returns and single and double quotes for Javascript segments.
     */
    function _escapeJs($javascript = '')
    {
        $javascript = preg_replace('/\r\n|\n|\r/', "\\n", $javascript);
        $javascript = preg_replace('/(["\'])/', '\\\\\1', $javascript);
        return $javascript;
    }

    function _methodJsFunction($method,$csrfIntention,$csrfField)
    {
        $function = "var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'post'; f.action = this.href;";

        //put, delete HTTP methods
        if ('post' != strtolower($method))
        {
            $function .= "var m = document.createElement('input'); m.setAttribute('type', 'hidden'); ";
            $function .= sprintf("m.setAttribute('name', '_method'); m.setAttribute('value', '%s'); f.appendChild(m);", strtolower($method));
        }

        // CSRF protection
        if ($csrfIntention)
        {
            /**
             * @todo isCsrfEnabled() - check a global config
             */
            if (TRUE)
            {
                $function .= "var m = document.createElement('input'); m.setAttribute('type', 'hidden'); ";
                $function .= sprintf("m.setAttribute('name', '%s'); m.setAttribute('value', '%s'); f.appendChild(m);", $csrfField, $this->csrfProvider->generateCsrfToken($csrfIntention));
            }
        }

        $function .= "f.submit();";
        return $function;
    }

    function _tagOptions(array $options = array())
    {
        $html = '';
        foreach ($options as $key => $value)
        {
            $html .= ' ' . $key . '="' . htmlspecialchars($value) . '"';
        }
        return $html;
    }

    public function getName()
    {
        return 'umbrellaweb_link';
    }
}

services.xml

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="umbrellaweb.twig.link_extension" class="UmbrellaWeb\Bundle\ExtraTwigBundle\Twig\LinkExtension">
            <tag name="twig.extension" />
            <argument type="service" id="form.csrf_provider" />
        </service>
    </services>
</container>

Now in twig you can use:

{{ link_to(path('jk_aa_admin_delete',{'id' : admin.id}),'<img src="del_icon.png"/>',
{'escape':false,'method':'delete','csrf_intention':'delete-admin',
'confirm':'Are you sure?'}) }}

I controller:

//check CSRF token
if (FALSE === $this->get('form.csrf_provider')->isCsrfTokenValid('delete-admin', $request->get('_token')))
{
throw new AccessDeniedHttpException('Invalid CSRF token.');
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T11:41:46+00:00Added an answer on June 12, 2026 at 11:41 am

    I had same problem. First I generated token in the Controller and passed to a twig file

     $intentions = 'unknown';  
     $csrfToken = $this->container->get('form.csrf_provider')->generateCsrfToken($intentions);
    
     return array('csrfToken'=>$csrfToken);
    

    than from the twig file you can access the token as

    var token = '{{csrfToken}}'
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can I be sure about the order in a Python dictionary? The function op.GetTangent(id)
Can I run this in a Windows command prompt like I can run it
Can anyone tell me how an IDE like NetBeans or any for that matter
Can somebody point me to a resource that explains how to go about having
Can anyone tell me how I can display a status message like 12 seconds
Can you please take a look at following link and let me know how
Can somebody recommend some papers (literature) or code snippets about tree-based diff algorithms for
Can anyone let me know how can we change the value of kendo combobox
Can I order my users in the database, so I don't have to say
Can I change the field public virtual ClassOne ClassOne { get; set; } to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.