Symfony gets form data in the 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 can I get the values ​​of user and password fields in the controller for working with them? I have a search, but I do not see a clear solution.

+6
source share
3 answers

Try this as an example and using Symfony2.8

Look:

  <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');
     ....
}

Another way to get the parameters, as you see, is not entirely intuitive:

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

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

You must pass the Request object to the action method, then process it:

public function conectionAction(Request $request){
    if ($request->getMethod() == Request::METHOD_POST){
        $user = $request->request->get('user');
        $password = $request->request->get('password');
    }
}

Symfony Form Component .

+2

Better check out the FOSUserBundle.

It is designed to control the login process.

http://symfony.com/doc/master/bundles/FOSUserBundle/index.html

-2
source

Source: https://habr.com/ru/post/1015762/


All Articles