Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony get form data in controller

I have this view:

//login.html.twig

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>MY APP</title>
</head>

<body>
    <form action="{{ path('conection') }}" method="post" name="formulario_login">
        <label for="username">User:</label>
        <input type="text" id="username" name="_username" value="{{ last_username|default('') }}" />
        <br />
        <label for="password">Password:</label>
        <input type="password" id="password" name="_password" />
        <br />
        <input type="checkbox" id="remember_me" name="_remember_me"/>
        <label for="remember_me">Remember me</label>
        <br />
        <input type="submit" name="login" value="Login" />
    </form>
</body>
</html>

In my routing file:

conection:
pattern:  /conection
defaults: { _controller: UserBundle:Default:conection}

And my controller

<?php

namespace myApp\UserBundle\Controller;

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

class DefaultController extends Controller
{
    //some other action functions

    public function conectionAction(){

    }
}

My question is how do I get in the controller the values of user and password fields to work with them?I have search but I don´t see a clear solution.

like image 383
SensacionRC Avatar asked Mar 15 '17 18:03

SensacionRC


1 Answers

Try this, by way of example and using Symfony2.8

View:

  <form action="{{ path('connection') }}" method="post" name="formulario_login">
        <label for="username">User:</label>
        <input type="text" id="username" name="_username" value="" />
        <br />
        <label for="password">Password:</label>
        <input type="password" id="password" name="_password" />
        <br />
        <input type="checkbox" id="remember_me" name="_remember_me"/>
        <label for="remember_me">Remember me</label>
        <br />
        <input type="submit" name="login" value="Login" />
    </form>

Controller:

public function connectionAction(Request $request) {
    $username = $request->request->get('_username');
    $password = $request->request->get('_password');
     ....
}

Other way to get parameters, as you can see the naming is not all that intuitive:

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

// $_POST parameters
$request->request->get('name');
like image 154
rescobar Avatar answered Oct 19 '22 13:10

rescobar