简体   繁体   中英

How to get user input with twig and symfony?

I have a simple add_user.html.twig that has a couple of input fields name, age, color I would like to pass (capture) the user input when the button is pressed and pass the values in these fields to the controller to be added to the database

add_user.html.twig


<body>
    <label for="username">User name:</label>
    <input type="text" id="username" name="_username" />

    <label for="color">Color:</label>
    <input type="text" id="color" name="_color" />

    <label for="age">Age:</label>
    <input type="text" id="age" name="_age" />

    <button type="submit">add</button>

</body>
</html>

inside UserController.php (inside the Controllers folder) i have a public function called create() which is responsible for adding the data to the database ending with

return new Response( $this->render('user/add_user.html.twig', [
    'controller_name' => 'UserController'
    ]));

now my question is how do I take the values entered by the user and pass them to the controller

As Cerad said, you can use Symfony form and Doctrine ORM. Symfony documentation is pretty well done.

Step by step is what I would personally do (there are several ways to accomplish that) :

-Create an entity User with all the fields you need like below with constraints, getters and setters.

/**
 * @var string
 * @ORM\Column(name="name", type="string", length=255)
 */
private $name;

/**
 * @return string
 */
public function getName(): string
{
    return $this->name;
}

/**
 * @param string $name
 */
public function setName(string $name): void
{
    $this->name = $name;
}

-Create a form AddUserType where you write all the fields and attributes like :

->add('name', TextType::class, [
    'label' => 'Your name : ',
    'attr' => [
                 'placeholder' => 'Name'
    ]
])

-Create a repository UserRepository (You can generate each file with Symfony command lines) to get method to request database. You can create your own methods here.

-Create a UserController where for example you code a new instance of User, new instance of AddUserType, get user informations, persist and flush inside database :

/**
 * @Route("/add_user", name="add_user")
 */
public function add_user(Request $request, EntityManagerInterface $em)
{
    //instance of User
    $user = new User();

    //instance of the form
    $addUserForm = $this->createForm(AddUserType::class, $user);

    //get infos
    $addUserForm->handleRequest($request);

    //Test if there is no error
    if ($addUserForm->isSubmitted() && $addUserForm->isValid())
    {
       
        //Validate and push infos inside database
        $em->persist($user);
        $em->flush();


        //Redirect to log in route if you want
        return $this->redirectToRoute("login");
    }

    //Give the form to Twig
    return $this->render('user/add_user.html.twig', [
        'controller_name' => 'UserController', "addUserForm" =>$addUserForm->createView()
    ]);
}

-Create the view (there are 3 ways to do it, but I recommend you to detail the form if you want more flexibility and to have a good looking form) :

{{ form_start(addUserForm)}}
    
           <!--add fields-->
           {{ form_label(addUserForm.name) }}
           {{ form_widget(addUserForm.name) }}
    
           <!--add other fields ..-->
    
           <!--add buttons-->
           <button type="submit">Register</button>
           <button type="reset">Cancel</button>
    
{{ form_end(addUserForm) }}

If you want to have the minimum to test it fast it's gonna look like :

{{ form_start(addUserForm) }}
{{ form_widget(addUserForm) }}
<button type="sumbit">Register!</button>
{{ form_end(addUserForm) }}

First make it simple to check if everything is working, and then you could add more parameters and more security like CSRF or password hash, flash message, errors, email, role etc..

(I don't know if I have to comment or to add another answer but anyway my message is too long for a comment..) The form builder object corresponds to the fields of your form, and a good practice is to code them inside the Type file (AddUserType) instead of inside the controller.

To create the AddUserType, there are some ways to do it but I recommend creating it from Composer :

-First go inside your Project folder from the console command. -Check if you already have the symfony/form and the symfony/maker-bundle components with this command :

composer show -i

If you have these lines it's okay, otherwise you have to install them :

composer require symfony/form
composer require symfony/maker-bundle

*If not already done before, you have to create your database and to synchronize your entities :

Php bin/console doctrine:database:create

*Check your env file inside your project to write your database informations, logs, username, password etc… It depends which database you're using. *Force your database to fit with entities :

Php bin/console doctrine:schema:update –force

-Generate the form from Composer :

Php bin/console make:form

-Fill all the fields, name, constraints, type etc (You have the possibility to adjust and correct this file after from your IDE) After that it's gonna generate the file for your project.

There is another solution but not recommended (because you have to manually create everything, your files, check all implemented classes or abstract classes, if you go for that, Symfony documentation is your best friend :p), you can go inside your IDE and create anything you need : You can organize your project but here is an example :

->src   ->Controller    ->UserController.php
                        ->AnyController.php
        ->Entity        ->User.php
                        ->AnyEntity.php
        ->Form          ->AddUserType.php
                        ->AnyType.php
        ->Repository    ->AddUserRepository.php
                        ->AnyRepository.php
->templates ->main      ->index.html.twig
            ->user      ->login.html.twig
                        ->add_user.html.twig
            ->base.html.twig

Anyway, after creating or generating the files, it's better to check if all the use are included, classes extend or implement the correct ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM