3

I want to get a parameter from a link in Symfony.

When I visit the URL, I should be forwarded to the index page. I want to get the value of the token parameter. The link looks like this:

http://www.myapp.com/?token=khdfhgkdfjghjdfgd354dfgdfg454dfg

In my controller, I should get the value of the token.
But how do I do this using the GET method?

0

2 Answers 2

6

This is a simple task, simply type hint the Request object in your controller method like so...

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class MyController extends Controller
{
    /**
     * @Route("/", name="index")
     */
    public function indexAction(Request $request)
    {
        $token = $request->query->get('token');

        // ... 
    }

    /**
     * @Route("/{token}", name="index_with_token")
     */
    public function indexWithTokenAction(Request $request, $token)
    {    
        // ... 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can do like this :

use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;


/**
* @Route("/your-url/{token}",
* defaults={"token"="...."}, name="url_token")
*/
public function yourAction(Request $request) {

    // $_GET parameters
    $request->query->get('name'); // in your case name is token

    // $_POST parameters
    $request->request->get('name');

}

6 Comments

Or you can put $token in the method arguments and symfony will automatically assign the value to the argument.
@Emna However, I strongly the council you to make some efforts and take a look at the official documentation!
What does the Request before the parameter $request mean?
@PomCanys It's typehint (Check out the PHP documentation). Symfony uses that in order to know which action parameter is the request parameter.
@EmanuelOster thank you for your explanation. So is Request something that only Symphony uses? Because on the PHP documentation I couldn't find Request as a valid type.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.