Quick user authentication and CRUD in Symfony 5

We will leverage on Symfony’s generators to quickly code a simple user authentication and CRUD system in less than 15 minutes.

Let’s start by creating a new Symfony project, which we will call sym_auth.

symfony new --full sym_auth

Then we will edit the .env file in the root folder, adding our database credentials.

DATABASE_URL=mysql://sym_auth:sym_auth@127.0.0.1:3306/sym_auth?serverVersion=5.7

Read more “Quick user authentication and CRUD in Symfony 5”

Symfony 5 – Select (or check box) for user roles in a form

For choosing between a html select or checkboxes on your form, just toggle the “multiple” parameter on the ChoiceType class. Since the roles are an array, we need a data transformer.

Example:

<?php

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\CallbackTransformer;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email')
            ->add('Roles', ChoiceType::class, [
                    'required' => true,
                    'multiple' => false,
                    'expanded' => false,
                    'choices'  => [
                      'User' => 'ROLE_USER',
                      'Partner' => 'ROLE_PARTNER',
                      'Admin' => 'ROLE_ADMIN',
                    ],
                ])

            ->add('password')
            ->add('groups')

        ;


        // Data transformer
        $builder->get('Roles')
            ->addModelTransformer(new CallbackTransformer(
                function ($rolesArray) {
                     // transform the array to a string
                     return count($rolesArray)? $rolesArray[0]: null;
                },
                function ($rolesString) {
                     // transform the string back to an array
                     return [$rolesString];
                }
        ));


    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

Set a bootstrap menu item as “active” in Symfony 5

In order to define a bootstrap menu item as “active” in a Symfony 5 project, you can add

{% set route_name = app.request.attributes.get('_route') %}

to the top of your base.html.twig. Then a twig condition in the navbar can be implemented as follows:

<li {% if route_name == "user_index" %} class="nav-item active" {% else %} class="nav-item" {% endif %} >

Read more “Set a bootstrap menu item as “active” in Symfony 5″

Symfony and Doctrine ORM – Many to many bidirectional relation

The classes below illustrate a many to many bidirectional relation with Doctrine ORM, Symfony3 and FOSUserBundle.

Entity User

<?php
// src/AppBundle/Entity/User.php

namespace AppBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="UserGroup", inversedBy="users")
     * @ORM\JoinColumn(name="usergroup_id", referencedColumnName="id")
     */
    private $usergroups;

    public function __construct()
    {
        parent::__construct();
        $this->usergroups = new ArrayCollection();
    }
}

Read more “Symfony and Doctrine ORM – Many to many bidirectional relation”