যারা বাংলাদেশের ৩৬ তম Zend Certified Engineer এবং এই সাইট (w3programmers) এর স্বত্বাধিকারী এবং লেখক Masud Alam স্যার এর কাছে কাছে সপ্তাহে ২ দিন ক্লাস, ৬ দিন প্রাকটিস করতে চান তাদের জন্য আগামী ১ February 2018 (বৃহস্পতি এবং শুক্রবার সন্ধ্যা ৬:০০ টা রাত ৯:০০ টা) থেকে শুরু হতে যাচ্ছে ৫ মাস ব্যাপী Professional Web Design & Development With HTML, CSS, JAVASCRIPT, JQUERY, PHP & MySQL for Beginners কোর্স (এই কোর্স টি যারা ফ্রিল্যান্সিং এবং আউটসোর্সিং কাজে আগ্রহী বিশেষ ভাবে তাদের জন্য design করা হয়েছে। ), আগামী ৪ February 2018 ( রবি এবং মঙ্গলবার সন্ধ্যা ৬:০০ টা থেকে রাত ৯:০০ টা ) থেকে শুরু হতে যাচ্ছে ৪ মাস ব্যাপী Zend Certified PHP 7.1 Engineering কোর্স। যেটা Advance PHP কোর্স নামে পরিচিত । এবং ৫ February 2018 (সোম এবং বুধবার সন্ধ্যা ৬:০০ টা থেকে রাত ৯:০০ টা) থেকে শুরু হতে যাচ্ছে ৪ মাস ব্যাপী Laravel 5.5 Professional Beginning to Advance Course কোর্স ।এই কোর্স গুলোতে তিনি ছাত্রদের কে সপ্তাহে ২ দিন ৩ ঘন্টা করে ৬ ঘন্টা ক্লাস নিবেন , এবং শনি থেকে বৃহস্পতি সপ্তাহে ৬ দিন ই স্যার এর অফিসে বসে প্রাকটিস করার সুযোগ দিবেন ! এতে প্রাকটিস করা কালীন ছাত্র-ছাত্রীরা কোনো সমস্যায় পড়লে তাৎক্ষণিক স্যার এর সহযোগিতা পাবে . (উল্লেখ্য: Training গুলো স্যার তার techbeeo software company'r পাশাপাশি পরিচালনা করে থাকেন।) কোর্স গুলো সম্পর্কে বিস্তারিত জানতে পারবেন এই লিংকে : Course Details .কোর্স গুলোর প্রত্যেকটির ফী নির্ধারণ করা হয়েছে ৩০,০০০ টাকা। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করার জন্য অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল নম্বর : ০১৭২২ ৮১ ৭৫ ৯১

User registration with Symfony

In this tutorial, we will learn about the registration of new users with Symfony2. Hope you have already read earlier tutorials. Because, this is an extension of previous one. We will work on the same code as well as we will also add more.

symfony

Let’s assume, we need to register our new users. For simplicity, we will only take username and password from the new user (but, anyway you can add more fields as you needed) and the admin will access to manage the users. New users only can view the book lists (And of course, you can add more functionality and make more smart system just changing in the view, nothing else). So, let’s start.

First we need to generate our user entity. And you have already known entities are work like model in Symfony.

Now open your command prompt and go to your project folder. And write the entity generation command.

$ php app/console doctrine:generate:entity

                                             
  Welcome to the Doctrine2 entity generator  
                                             


This command helps you generate Doctrine2 entities.

First, you need to give the entity name you want to generate.
You must use the shortcut notation like AcmeBlogBundle:Post.

The Entity shortcut name: CustomBookBundle:User

Determine the format to use for the mapping information.

Configuration format (yml, xml, php, or annotation) [annotation]: 

Instead of starting with a blank entity, you can add some fields now.
Note that the primary key will be added automatically (named id).

Available types: array, simple_array, json_array, object, 
boolean, integer, smallint, bigint, string, text, datetime, datetimetz, 
date, time, decimal, float, blob, guid.

New field name (press <return> to stop adding fields): username
Field type [string]: 
Field length [255]: 50

New field name (press <return> to stop adding fields): password
Field type [string]: 
Field length [255]: 64

New field name (press <return> to stop adding fields): 

Do you want to generate an empty repository class [no]? 

                             
  Summary before generation  
                             

You are going to generate a "CustomBookBundle:User" Doctrine2 entity
using the "annotation" format.

Do you confirm generation [yes]? 

                     
  Entity generation  
                     

Generating the entity code: OK

                                               
  You can now start using the generated code!  
                                               

$

Yes, our entity is done. Now go to src/Custom/BookBundle/Entity/User.php, which contains our user entity code. For the sake of interaction with user and the database, we need to use UserInterface interface. So, let’s do it as follows-


namespace Custom\BookBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * User
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class User implements UserInterface
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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

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


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set username
     *
     * @param string $username
     * @return User
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string 
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Set password
     *
     * @param string $password
     * @return User
     */
    public function setPassword($password)
    {
        $this->password = password_hash($password, PASSWORD_BCRYPT) ;

        return $this;
    }

    /**
     * Get password
     *
     * @return string 
     */
    public function getPassword()
    {
        return $this->password;
    }

    public function getSalt(){
        return null;
    }

    public function getRoles(){
        return array('ROLE_USER');
    }

    public function eraseCredentials(){

    }
}

Need to be mention, UserInterface is an interface, so it has three methods, we need to implement, getSalt(),getRoles(), eraseCredentials(). Here, getRoles() will return ‘ROLE_USER‘ role.

In our setPassword() method in line no 79, we have encrypt user password using bcrypt.

Now again in the command prompt write the following command to push the entity to the database, so that it can create table for our users. No need to be worried. Our previous table will be intact.

$ php app/console doctrine:schema:update --force
Updating database schema...
Database schema updated successfully! "2" queries were executed
$

You can check your database with phpmyadmin, if our new table has created. If everything is fine, you will see a new table has created in our database with two fields, username and password.

Now we will create our CRUD through command prompt. We have done this before, can you remember!!!

$ php app/console generate:doctrine:crud 
                                           
  Welcome to the Doctrine2 CRUD generator  
                                           


This command helps you generate CRUD controllers and templates.

First, you need to give the entity for which you want to generate a CRUD.
You can give an entity that does not exist yet and the wizard will help
you defining it.

You must use the shortcut notation like AcmeBlogBundle:Post.

The Entity shortcut name: CustomBookBundle:User

By default, the generator creates two actions: list and show.
You can also ask it to generate "write" actions: new, update, and delete.

Do you want to generate the "write" actions [no]? yes

Determine the format to use for the generated CRUD.

Configuration format (yml, xml, php, or annotation) [annotation]: yml

Determine the routes prefix (all the routes will be "mounted" under this
prefix: /prefix/, /prefix/new, ...).

Routes prefix [/user]: 

                             
  Summary before generation  
                             

You are going to generate a CRUD controller for "CustomBookBundle:User"
using the "yml" format.

Do you confirm generation [yes]? 

                   
  CRUD generation  
                   

Generating the CRUD code: OK
Generating the Form code: OK
Confirm automatic update of the Routing [yes]? 
Importing the CRUD routes: OK

                                               
  You can now start using the generated code!  
                                               

$

You can check the controller folder; a new controller has created for user as well as the view.

By default, in our form the password field type is text. We want to change it password. Because logical, right?

So open src/Custom/BookBundle/Form/UserType.php and add the field type as password in line 5.

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username')
            ->add('password', 'password')
        ;
    }

At this moment, we need to configure our security in app/config/security.yml

security:
    encoders:
      Symfony\Component\Security\Core\User\User: plaintext
      Custom\BookBundle\Entity\User: bcrypt
    role_hierarchy:
      ROLE_ADMIN: [ROLE_USER]
    providers:
      chain_provider:
        chain:
          providers: [in_memory, user_db]
      in_memory:
        memory:
          users:
            admin: {password: adminpass, roles: ROLE_ADMIN}
      user_db:
        entity: {class: CustomBookBundle:User, property: username}
    firewalls:
      main:
        pattern: /.*
        form_login:
          login_path: /login
          check_path: /login_check
          default_target_path: /book
        logout:
          path: /logout
          target: /book
        security: true
        anonymous: true


    access_control:
      - { path: /login, roles: [IS_AUTHENTICATED_ANONYMOUSLY, ROLE_USER] }
      - { path: /user/edit, roles: ROLE_ADMIN }
      - { path: /user/index, roles: ROLE_ADMIN }
      - { path: /user/show, roles: ROLE_ADMIN }
      - { path: /user/new, roles: IS_AUTHENTICATED_ANONYMOUSLY }
      - { path: /.*, roles: [IS_AUTHENTICATED_ANONYMOUSLY, ROLE_USER] }
 

If you check carefully, in line 4 we have added bcrypt, so that the password can be hashed.

Rest of the code is same, until line 33. We have added some more access control for our admin and anonymous user.

Again we need to change our navbar, a little bit to check the user access. So open
app/Resources/views/base.html.twig and edit.

<div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a href="{{ path('book') }}">Home</a></li>

                    {% if is_granted('ROLE_ADMIN') %}
                        <li><a href="{{ path('logout') }}">Logout</a></li>
                        <li><a href="{{ path('user') }}">User</a></li>
                    {% elseif is_granted('ROLE_USER') %}
                        <li><a href="{{ path('logout') }}">Logout</a></li>
                    {% else %}
                        <li><a href="{{ path('login') }}">Login</a></li>
                        <li><a href="{{ path('user_new') }}">Register</a></li>
                    {% endif %}
                </ul>
            </div>

We need to delete some code from src/Custom/BookBundle/Resources/views/User/new.html.twig as we don’t want, the user will see the user list.

{% extends '::base.html.twig' %}

{% block body -%}
    <h1>User creation</h1>

    {{ form(form) }}

{% endblock %}

We are almost done. After register we need to redirect our user to login page. So open src/Custom/BookBundle/Controller/UserController.php and change the login path in line 12.

public function createAction(Request $request)
    {
        $entity = new User();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('login'));
        }

        return $this->render('CustomBookBundle:User:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

Yes we are all done. Now open your browser and try to register and login –

http://localhost/symfony/web/app_dev.php/book/.

Register —

register

User control by admin —

User Control

By the way, you can download all the code from my –

Happy coding… 🙂

User registration with Symfony

Hej, I’m from Bangladesh. Learning programming is one of the freaking decisions I have taken in my life. Because, it makes me and my life crazy. I have great weakness on open source technologies. Perhaps, that’s why I do not know any closed source language. I fall in love with programming, when I started my undergraduate in East West University. Till now, I can not live without it.

4 comments on “User registration with Symfony
  1. Can you help me, thanks

    I found this error:
    An exception has been thrown during the rendering of a template (“Unable to generate a URL for the named route “login” as such route does not exist.”) in ::base.html.twig at line 11.

Leave a Reply

Your email address will not be published. Required fields are marked *