Controller - Symfony - an overview of its features with

Lecture



Это продолжение увлекательной статьи про symfony .

...

follows.

php bin/console generate:bundle --namespace = Tutorialspoint/DemoBundle

Result

Welcome to the Symfony bundle generator!

Are you planning on sharing this bundle across multiple applications? [no]: no

Your application code must be written in bundles. This command helps
you generate them easily.

Give your bundle a descriptive name, like BlogBundle.
Bundle name [Tutorialspoint/DemoBundle]:

In your code, a bundle is often referenced by its name. It can be the
concatenation of all namespace parts but it's really up to you to come
up with a unique name (a good practice is to start with the vendor name).
Based on the namespace, we suggest TutorialspointDemoBundle.

Bundle name [TutorialspointDemoBundle]:
Bundles are usually generated into the src/ directory. Unless you're
doing something custom, hit enter to keep this default!
Target Directory [src/]:

What format do you want to use for your generated configuration?

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

Bundle generation

> Generating a sample bundle skeleton into app/../src/Tutorialspoint/DemoBundle
   created ./app/../src/Tutorialspoint/DemoBundle/
   created ./app/../src/Tutorialspoint/DemoBundle/TutorialspointDemoBundle.php
   created ./app/../src/Tutorialspoint/DemoBundle/Controller/
   created ./app/../src/Tutorialspoint/DemoBundle/Controller/DefaultController.php
   created ./app/../tests/TutorialspointDemoBundle/Controller/
   created ./app/../tests/TutorialspointDemoBundle/Controller/DefaultControllerTest.php
   created ./app/../src/Tutorialspoint/DemoBundle/Resources/views/Default/
   created ./app/../src/Tutorialspoint/DemoBundle/Resources/views/Default/index.html.twig
   created ./app/../src/Tutorialspoint/DemoBundle/Resources/config/
   created ./app/../src/Tutorialspoint/DemoBundle/Resources/config/services.yml
> Checking that the bundle is autoloaded
> Enabling the bundle inside app/AppKernel.php
   updated ./app/AppKernel.php
> Importing the bundle's routes from the app/config/routing.yml file
   updated ./app/config/routing.yml
> Importing the bundle's services.yml from the app/config/config.yml file
   updated ./app/config/config.yml
Everything is OK! Now get to work :).

Creating a Simple Web Application

This chapter explains how to create a simple application in the Symfony framework. As discussed earlier, you already know how to create a new project in Symfony.

We can take the example of “student” details. Let us start by creating a project named “student” using the following command.

symfony new student

After executing the command, an empty project is created.

Controller

Symfony is based on the Model-View-Controller (MVC) design pattern. MVC is a software approach that separates the application logic from the view. The controller plays an important role in the Symfony Framework. Every web page in the application must be handled by a controller.

The DefaultController class is located in “src / AppBundle / Controller” . There, you can create your own Controller class.

Go to the “src / AppBundle / Controller” folder and create a new StudentController class.

Below is the basic syntax for the StudentController class.

StudentController.php

namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
class StudentController {
}

You have now created StudentController. In the next chapter, we will discuss the controller in more detail.

Create a Route

Once the Controller has been created, we need to route it to a specific page. Routing maps the request URI to a specific controller method.

Below is the basic syntax for routing.

namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class StudentController {
   /**
      * @Route("/student/home")
   */
   public function homeAction() {
      return new Response('Student details application!');
   }
}

In the syntax above, @Route (“/ student / home”) is the route. It defines the URL pattern for the page.

homeAction () is the action method, in which you can build the page and return a Response object.

We will look at routing in detail in the next chapter. Now request the URL “http: // localhost: 8000 / student / home”, and it will give the following result.

Result

Symfony - an overview of its features with examples

Symfony — Controllers

The controller is responsible for handling every request coming into the Symfony application. The controller reads information from the request. It then creates and returns a response object to the client.

In Symfony, the DefaultController class is located in “src / AppBundle / Controller” . It is defined as follows.

DefaultController.php



Here, the HttpFoundation component defines an object-oriented layer for the HTTP specification, and FrameworkBundle contains most of the “core” framework functionality.

Request Object

The Request class is an object-oriented representation of the HTTP request message.

Creating a Request Object

A request can be created using the createFromGlobals () method .

use Symfony\Component\HttpFoundation\Request;
$request = Request::createFromGlobals();

You can simulate a request using Globals. Instead of creating a request based on PHP global variables, you can also simulate a request.

$request = Request::create(
   '/student',
   'GET',
   array('name' => 'student1')
);

Here, the create () method creates a request based on a URI, a method, and some parameters.

Overriding the Request Object

You can override PHP global variables using the overrideGlobals () method . It is defined as follows.

$request->overrideGlobals();

Accessing the Request Object

The web page can be accessed inside the controller (action method) using the base controller's getRequest () method.

$request = $this->getRequest();

Identifying the Request Object

If you want to identify the request in your application, the PathInfo method will return a unique identifier for the request URL. It is defined as follows.

$request->getPathInfo();

Response Object

The only requirement of a controller is to return a Response object. The Response object contains all the information from a given request and sends it back to the client.

Below is a simple example.

Example

use Symfony\Component\HttpFoundation\Response;
$response = new Response(‘Default'.$name, 10);

You can define the Response object in JSON as follows.

$response = new Response(json_encode(array('name' => $name)));
$response->headers->set('Content-Type', 'application/json');

Response Constructor

The constructor takes three arguments —

  • The response content
  • The status code
  • An array of HTTP headers

Below is the basic syntax.

use Symfony\Component\HttpFoundation\Response;
$response = new Response(
   'Content',
   Response::HTTP_OK,
   array('content-type' => 'text/html')
);

For example, you can pass the content argument as,

$response->setContent(’Student details’);

In the same way, you can pass the other arguments too.

Sending the Response

You can send the response to the client using the send () method . It is defined as follows.

$response->send();

To redirect the client to another URL, you can use the RedirectResponse class.

It is defined as follows.

use Symfony\Component\HttpFoundation\RedirectResponse;
$response = new RedirectResponse('http://tutorialspoint.com/');

FrontController

A single PHP file that handles every request coming into your application. The FrontController performs the routing of different URLs to the internal parts of the application.

Below is the basic syntax of a FrontController.

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$request = Request::createFromGlobals();
$path = $request->getPathInfo(); // the URI path being requested

if (in_array($path, array('', '/')))  {
   $response = new Response(’Student home page.');
} elseif (‘/about’ === $path) {
   $response = new Response(’Student details page’);
} else {
   $response = new Response('Page not found.', Response::HTTP_NOT_FOUND);
}
$response->send();

Here, the in_array () function looks for a specific value in an array.

Symfony — Routing

Routing maps a request URI to a specific controller method. In general, any URI consists of the following three parts:

  • Host name
  • Path segment
  • Query segment

For example, in the URI / URL http://www.tutorialspoint.com/index?q=data, www.tutorialspoint.com is the host name segment, index is the path segment, and q = data is the query segment. In general, routing checks the page segment against a set of constraints. If a constraint matches, it returns a set of values. One of the main values is the controller.

Annotations

Annotations play an important role in configuring a Symfony application. Annotation simplifies configuration by declaring the configuration right within the code itself. An annotation is nothing but a way of providing meta-information about a class, methods, and properties. Routing makes wide use of annotations. Even though routing can be done without annotations, annotations make routing much simpler.

Below is an example of an annotation.

/**
   * @Route(“/student/home”)
*/
public function homeAction() {
   // ...
}

Routing Concepts

Consider the StudentController, class created in the “student” project.

StudentController.php

// src/AppBundle/Controller/StudentController.php
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class StudentController extends Controller {
   /**
      * @Route(“/student/home”)
   */
   public function homeAction() {
      // ...
   }

   /**
      * @Route(“/student/about”)
   */
   public function aboutAction() {
   }
} 

Here, routing is done in two stages. If you go to / student / home , the first route matches, and then homeAction () executes . Otherwise, if you go to / student / about , the second route is found, and then aboutAction () executes .

Adding Wildcards

Suppose you have a numbered list of student records with URLs like / student / 2 and / student / 3 for pages 2 and 3 respectively. Then, if you want to change the route path, you can use wildcard formats.

Example

// src/AppBundle/Controller/BlogController.php
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class StudentController extends Controller {
   /**
      * @Route(“/student/{page}", name = “student_about”, requirements = {"page": "\d+"})
   */
   public function aboutAction($page) {
      // ...
   }
} 

Here, \ d + is a regular expression that matches a digit of any length.

Assigning a Placeholder

You can assign a default value to a placeholder in routing. It is defined as follows.

// src/AppBundle/Controller/BlogController.php
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class StudentController extends Controller {
   /**
      * @Route(“/student/{page}", name = “student_about”, requirements = {"page": "\d+"})
   */

   public function aboutAction($page = 1) {
      // ...
   }
}

Here, if you go to / student, the student_about route will match, and $ page will default to 1.

Redirecting to a Page

If you want to redirect the user to another page, use the redirectToRoute () and redirect () methods.

public function homeAction() {
   // redirect to the "homepage" route
   return $this->redirectToRoute('homepage');

   // redirect externally
   \return $this->redirect('http://example.com/doc');
}

Generating a URL

To generate a URL, consider the route name, student name, and the wildcard, student names, used in the path for that route. The full listing for generating the URL is defined as follows.

class StudentController extends Controller {
   public function aboutAction($name) {
      // ...
      // /student/student-names
      $url = $this->generateUrl(
         ‘student_name’,
         array(‘name’ =>
         ’student-names’)
      );
   }
}

StudentController

Consider the following simple routing example in the StudentController class.

StudentController.php

Project: '.$name.''
      );
   }
}

Now request the URL “http: // localhost: 8000 / student / home”, and it will give the following result.

Symfony - an overview of its features with examples

In the same way, you can create another route for aboutAction () .

Symfony — View Engine

The view layer is the presentation layer of an MVC application. It separates the application logic from the presentation logic.

When the controller needs to generate HTML, CSS, or any other content, it forwards the task to the template engine.

Templates

Templates are basically text files used to generate any text-based document, such as HTML, XML, and so on. They are used to save time and reduce the number of errors.

By default, templates can live in two different locations:

app / Resources / views / — The application's view directory can contain the layouts and templates of your application. It also overrides third-party bundle templates.

vendor / path / to / Bundle / Resources / views / — Each third-party bundle keeps its templates in its own “Resources / views /” directory.

Twig Engine

Symfony uses a powerful template language called Twig . Twig makes it very easy to build concise, readable templates. Twig templates are simple and will not process PHP tags. Twig performs whitespace control, sandboxing, and automatic HTML escaping.

Syntax

Twig has three kinds of special syntax —

  • {{…}} — prints a variable or the result of an expression to the template.

  • {% …%} — a tag that controls the template logic. It is mainly used to execute a function.

  • {# … #} — Comment syntax. Used to add single-line or multi-line comments.

{{…}} — prints a variable or the result of an expression to the template.

{% …%} — a tag that controls the template logic. It is mainly used to execute a function.

{# … #} — Comment syntax. Used to add single-line or multi-line comments.

The base Twig template is located at “app / Resources / views / base.html.twig” .

Example

Let us look at a simple example using the Twig engine.

StudentController.php

render('student/home.html.twig');
   }
}

Here, the render () method renders the template and puts its content into the Response object.

Now go to the “views” directory and create a “student” folder, and inside that folder create a “home.html.twig” file. Add the following changes to the file.

home.html.twig

//app/Resources/views/student/home.html.twig

Student application!

You can get the result by requesting the URL “http: // localhost: 8000 / student / home”.

By default, Twig comes with a long list of tags, filters, and functions. Let us go through them one by one in detail.

Tags

Twig supports the following important tags —

Do

The do tag performs functions similar to a regular expression, except that it does not print anything. Its syntax is as follows —

{% do 5 + 6 %}

Include

The include statement includes a template and returns the rendered content of that file into the current namespace. Its syntax is as follows —

{% include 'template.html' %}

Extends

The extends tag can be used to extend one template from another. Its syntax is as follows —

{% extends "template.html" %}

Block

A block acts as a placeholder and replaces content. Block names consist of alphanumeric characters and underscores. For example,

{% block title %}{% endblock %}

Embed

The embed tag performs a combination of include and extends. It allows you to include the content of another template. It also allows you to override any block defined inside the included template, similar to extending a template. Its syntax is as follows —

{% embed “new_template.twig” %}
   {# These blocks are defined in “new_template.twig" #}
   {% block center %}
      Block content
   {% endblock %}
{% endembed %}

Filter

Filter sections allow you to apply regular Twig filters to a block of template data. For example,

{% filter upper %}
   symfony framework
{% endfilter %} 

Here, the text will be changed to upper case.

For

The for loop iterates over each item in a sequence. For example,

{% for x in 0..10 %}
   {{ x }}
{% endfor %}

If

The if statement in Twig is similar to PHP. An expression is evaluated as true or false. For example,

{% if value == true %}
   

Simple If statement

{% endif %}

Filters

Twig has filters. They are used to modify content before it is rendered. Below are some of the well-known filters.

Length

The length filter returns the length of a string. Its syntax is as follows —

{% if name|length > 5 %}
   ...
{% endif %}

Lower

The lower filter converts a value to lower case. For example,

{{ 'SYMFONY'|lower }}

This would give the following result —

symfony

In the same way, you can try upper case.

Replace

The replace filter formats a given string by replacing placeholders. For example,

{{ "tutorials point site %si% and %te%."|replace({'%si%': web, '%te%': "site"}) }} 

This would give the following result —

tutorials point website

Title

The title filter returns the title-case version of a value. For example,

{{ 'symfony framework '|title }}

This would give the following result —

 Symfony Framework

Sort

The sort filter sorts an array. Its syntax is as follows —

{% for user in names|sort %}
   ...
{% endfor %}

Trim

The trim filter removes whitespace (or other characters) from the beginning and end of a string. For example,

{{ '  Symfony!  '|trim }} 

This would give the following result —

Symfony!

Functions

Twig supports functions. They are used to obtain a specific result. Below are some important Twig functions.

Attribute

The attribute function can be used to access a “dynamic” attribute of a variable. Its syntax is as follows —

{{ attribute(object, method) }}
{{ attribute(object, method, arguments) }}
{{ attribute(array, item) }}

For example,

{{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }}

Constant

The Constant function returns the constant value for a given string. For example,

{{ constant('Namespace\\Classname::CONSTANT_NAME') }}

Cycle

The cycle function cycles through an array of values. For example,

{% set months = [‘Jan’, ‘Feb’, ‘Mar’] %}
{% for x in 0..12 %}
   { cycle(months, x) }}
{% endfor %}

Date

Converts the argument to a date to allow date comparison. For example,

Choose your location before {{ 'next Monday'|date('M j, Y') }}

This would give the following result —

Choose your location before May 15, 2017

The argument must be in one of the supported PHP date and time formats.

You can pass a time zone as the second argument.

Dump

The dump function outputs information about a template variable. For example,

{{ dump(user) }}

Max

The max function returns the largest value in a sequence. For example,

{{ max(1, 5, 9, 11, 15) }}

Min

The min function returns the smallest value in a sequence. For example,

{{ min(1, 3, 2) }}

Include

The include function returns the rendered content of a template. For example,

{{ include('template.html') }}

Random

The random function generates a random value. For example,

{{ random([‘Jan’, ‘Feb’, ‘Mar’, ‘Apr’]) }}
{# example output: Jan #}

Range

The Range function returns a list containing an arithmetic sequence of integers. For example,

{% for x in range(1, 5) %}
   {{ x }},
{% endfor %}

This would give the following result —

1,2,3,4,5

Layouts

A layout represents the common parts of multiple views, such as the page header and footer.

Template Inheritance

A template can be used by another. We can achieve this using the concept of template inheritance. Template inheritance lets you build a base “layout” template that contains all the common elements of your site, defined as blocks.

Let us look at a simple example to understand template inheritance better.

Example

Consider the base template located at “app / Resources / views / base.html.twig”. Add the following changes to the file.

base.html.twig



   
      
      {% block title %}Parent template Layout{% endblock %}
   

Now go to the index template file located at “app / Resources / views / default / index.html.twig” . Add the following changes to it.

index.html.twig

{% extends 'base.html.twig' %}
{% block title %}Child template Layout{% endblock %}

Here, the {% extends%} tag tells the template engine to first evaluate the base template, which sets up the layout and defines the block. Then the child template is rendered. The child template can extend the base layout and overwrite the title block. Now request the URL “http: // localhost: 8000”, and you will be able to get its result.

Assets

The Asset component manages URL generation and versioning of web resources such as CSS stylesheets, JavaScript files, and image files.

JavaScript

To include JavaScript files, use the javascripts tag in any template.

{# Include javascript #}
{% block javascripts %}
   {% javascripts '@AppBundle/Resources/public/js/*' %}
      
   {% endjavascripts %}
{% endblock %}

Stylesheets

To include stylesheet files, use the stylesheets tag in any template.

{# include style sheet #}
{% block stylesheets %}
   {% stylesheets 'bundles/app/css/*' filter = 'cssrewrite' %}
      
   {% endstylesheets %}
{% endblock %}

Images

To include an image, you can use the image tag. It is defined as follows.

{% image '@AppBundle/Resources/public/images/example.jpg' %}
   Example
{% endimage %}

Combined Assets

You can combine many files into one. This helps reduce the number of HTTP requests and improves front-end performance.

{% javascripts
   '@AppBundle/Resources/public/js/*'
   '@AcmeBarBundle/Resources/public/js/form.js'
   '@AcmeBarBundle/Resources/public/js/calendar.js' %}
   
{% endjavascripts %}

Symfony — Doctrine ORM

In the Symfony web framework, the model plays an important role. Models represent business entities. They are either provided by clients or fetched from a back-end database, processed according to business rules, and saved back to the database. This is the data represented by the views. Let us learn about models and how they interact with the back-end system in this chapter.

Database Model

We need to map our models to the internals of a relational database so as to retrieve and save models safely and efficiently. This mapping can be done with an Object Relational Mapping (ORM) tool. Symfony provides a separate DoctrineBundle , which integrates Symfony with a third-party PHP database ORM tool, Doctrine .

Doctrine ORM

By default, the Symfony framework does not provide any components for working with databases. But it integrates tightly with Doctrine ORM . Doctrine contains several PHP libraries used for database storage and object mapping.

The following example will help you understand how Doctrine works, how to configure the database, and how to save and retrieve data.

Doctrine ORM Example

In this example, we will first set up the database and create a Student object, and then perform some operations on it.

To do this, we need to follow the steps below.

Step 1: Create a Symfony Application

Create a Symfony application, dbsample, using the following command.

 symfony new dbsample

Step 2: Configure the Database

Typically, database information is configured in the “app / config / parameters.yml” file.

Open the file and add the following changes.

parameter.yml

parameters:
   database_host: 127.0.0.1
   database_port: null
   database_name: studentsdb
   database_user: 
   database_password: 
   mailer_transport: smtp
   mailer_host: 127.0.0.1
   mailer_user: null
   mailer_password: null
   secret: 037ab82c601c10402408b2b190d5530d602b5809

   doctrine:
      dbal:
      driver:   pdo_mysql
      host:     '%database_host%'
      dbname:   '%database_name%'
      user:     '%database_user%'
      password: '%database_password%'
      charset: utf8mb4

Now Doctrine ORM can connect to the database.

Step 3: Create the Database

Run the following command to create the “studentdb” database. This step is used to bind the database in Doctrine ORM.

php bin/console doctrine:database:create

Once the command executes, it automatically generates an empty “studentdb” database. You can see the following response on your screen.

Created database `studentsdb` for connection named default

Step 4: Mapping Information

Mapping information is nothing but “metadata”. It is a set of rules that tells Doctrine ORM how the Student class and its properties are mapped to a specific database table.

Well, this metadata can be specified in several different formats, including YAML, XML, or you can annotate the Student class directly using annotations. It is defined as follows.

Student.php

Add the following changes to the file.



Here, the table name is optional. If the table name is not specified, it will be determined automatically based on the entity class name.

Step 5: Bind the Entity

Doctrine generates simple entity classes for you. This will help you build any entity.

Run the following command to generate the entity.

php bin/console doctrine:generate:entities AppBundle/Entity/Student

You will then see the following result, and the entity will be updated.

Generating entity "AppBundle\Entity\Student"
   > backing up Student.php to Student.php~
   > generating AppBundle\Entity\Student

Student.php

id;
   }

   /**
      * Set name
      *
      * @param string $name
      *
      * @return Student
   */

   public function setName($name) {
      $this->name = $name;
      return $this;
   }

   /**
      * Get name
      *
      * @return string
   */

   public function getName() {
      return $this->name;
   }

   /**
      * Set address
      *
      * @param string $address
      *
      * @return Student
   */

   public function setAddress($address) {
      $this->address = $address;
      return $this;
   }

   /**
      * Get address
      *
      * @return string
   */

   public function getAddress() {
      return $this->address;
   }
}

Step 6: Validate the Mapping

After creating the entities, you should validate the mappings using the following command.

php bin/console doctrine:schema:validate

This would give the following result —

[Mapping]  OK - The mapping files are correct.
[Database] FAIL - The database schema is not in sync with the current mapping file

Since we have not created the students table, the entity is out of sync. Let us create the students table using the Symfony command in the next step.

Step 7: Create the Schema

Doctrine can automatically create all the database tables required for the Student entity. This can be done using the following command.

php bin/console doctrine:schema:update --force

After executing the command, you can see the following response.

Updating database schema...
Database schema updated successfully! "1" query was executed

This command compares how your database should look with how it actually looks, and executes the SQL statements needed to update the database schema to where it should be.

Now check the schema again using the following command.

php bin/console doctrine:schema:validate

This would give the following result —

[Mapping]  OK - The mapping files are correct.
[Database] OK - The database schema is in sync with the mapping files

Step 8: Getter and Setter

As seen in the “Bind the Entity” section, the following command generates all the getter and setter methods for the Student class.

$ php bin/console doctrine:generate:entities AppBundle/Entity/Student

Step 9: Saving Objects to the Database

Now we have mapped the Student entity to the corresponding Student table. Now we should be able to save Student objects to the database. Add the following method to the bundle's StudentController.

StudentController.php

setName('Adam'); 
      $stud->setAddress('12 north street'); 
      $doct = $this->getDoctrine()->getManager();
      
      // tells Doctrine you want to save the Product 
      $doct->persist($stud);
      
      //executes the queries (i.e. the INSERT query) 
      $doct->flush(); 
      
      return new Response('Saved new student with id ' . $stud->getId()); 
   } 
} 

Here we accessed the Doctrine manager using the getManager() method through the base controller's getDoctrine(), and then saved the current object using the Doctrine manager's persist() method. The persist() method queues the command, but the flush() method does the actual work (saving the student object).

Step 10: Fetching Objects from the Database

Create a function in StudentController that will display the student's details.

StudentController.php

/** 
   * @Route("/student/display") 
*/ 
public function displayAction() { 
   $stud = $this->getDoctrine() 
   ->getRepository('AppBundle:Student') 
   ->findAll();
   return $this->render('student/display.html.twig', array('data' => $stud)); 
}            

Step 11: Create a View

Let us create a view that points to the display action. Go to the views directory and create the file “display.html.twig”. Add the following changes to the file.

display.html.twig

 

Students database application!

{% for x in data %} {% endfor %}
Name Address
{{ x.Name }} {{ x.Address }}

You can get the result by requesting the URL “http: // localhost: 8000 / student / display” in the browser.

It will produce the following output on the screen —

Symfony - an overview of its features with examples

Step 12: Update an Object

To update an object in StudentController, create an action and add the following changes.

/** 
   * @Route("/student/update/{id}") 
*/ 
public function updateAction($id) { 
   $doct = $this->getDoctrine()->getManager(); 
   $stud = $doct->getRepository('AppBundle:Student')->find($id);  
   
   if (!$stud) { 
      throw $this->createNotFoundException( 
         'No student found for id '.$id 
      ); 
   } 
   $stud->setAddress('7 south street'); 
   $doct->flush(); 
   
   return new Response('Changes updated!'); 
}

Now request the URL “http: // localhost: 8000 / Student / update / 1”, and it will give the following result.

It will produce the following output on the screen —

Symfony - an overview of its features with examples

Step 13: Delete an Object

Deleting an object is similar and requires calling the entity manager's (Doctrine's) remove() method.

This can be done using the following command.

/** 
   * @Route("/student/delete/{id}") 
*/ 
public function deleteAction($id) { 
   $doct = $this->getDoctrine()->getManager(); 
   $stud = $doct->getRepository('AppBundle:Student')->find($id);  
    
   if (!$stud) { 
      throw $this->createNotFoundException('No student found for id '.$id); 
   }  
    
   $doct->remove($stud); 
   $doct->flush();  
   
   return new Response('Record deleted!'); 
}

Symfony — Forms

Symfony provides various built-in tags for easy and secure handling of HTML forms. The Symfony Form component handles the process of building and validating a form. It connects the model and the view layer. It provides a set of form elements for building a full-fledged HTML form from predefined models. This chapter explains forms in detail.

Form Fields

The Symfony Framework API supports a large group of field types. Let us look at each of the field types in detail.

FormType

It is used to generate a form within Symfony. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\TextType; 
use Symfony\Component\Form\Extension\Core\Type\EmailType; 
use Symfony\Component\Form\Extension\Core\Type\FormType; 
// ...  

$builder = $this->createFormBuilder($studentinfo); 
$builder 
   ->add('title', TextType::class);

Here $studentinfo is an entity of type Student. createFormBuilder is used to create the HTML form. The add method is used to add input elements inside the form. title refers to the student's title property. TextType::class refers to the HTML text field. Symfony provides classes for all HTML elements.

TextType

The TextType field is the most basic text input field. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\TextType; 
$builder->add(‘name’, TextType::class); 

Here name is mapped to the entity.

TextareaType

Renders an HTML textarea element. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\TextareaType; 
$builder->add('body', TextareaType::class, array( 
   'attr' => array('class' => 'tinymce'), 
));

EmailType

The EmailType field is a text field rendered using the HTML5 email tag. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\EmailType; 
$builder->add('token', EmailType::class, array( 
   'data' => 'abcdef', )); 

PasswordType

The PasswordType field displays a password text input. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\PasswordType; 
$bulder->add('password', PasswordType::class); 

RangeType

The RangeType field is a slider that is rendered using the HTML5 range tag. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\RangeType; 
// ...  
$builder->add('name', RangeType::class, array( 
   'attr' => array( 
      'min' => 100, 
      'max' => 200 
   ) 
));

PercentType

PercentType renders a text input field and specializes in handling percentage data. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\PercentType; 
// ... 
$builder->add('token', PercentType::class, array( 
   'data' => 'abcdef', 
));

DateType

Renders a date format. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\DateType; 
// ... 
$builder->add(‘joined’, DateType::class, array( 
   'widget' => 'choice', 
)); 

Here, widget is the main way in which the field is rendered.

It supports the following options.

  • choice — renders three select inputs. The order of the selects is determined by the format option.

  • text — renders three text type input fields (month, day, year).

  • single_textrenders a single date input type. User input is validated based on the format option.

choice — renders three select inputs. The order of the selects is determined by the format option.

text — renders three text type input fields (month, day, year).

single_textrenders a single date input type. User input is validated based on the format option.

CheckboxType

Creates a single checkbox input. This should always be used for a field that has a boolean value. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\CheckboxType; 
// ...  
$builder-

RadioType

Creates a single radio button. If the radio button is selected, the field will be set to the specified value. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\RadioType; 
// ...  
$builder->add('token', RadioType::class, array( 
   'data' => 'abcdef', 
));

Note that radio buttons cannot be unchecked — the value only changes when a different radio button with the same name is selected.

RepeatedType

This is a special “group” field that creates two identical fields whose values must match. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\RepeatedType; 
use Symfony\Component\Form\Extension\Core\Type\PasswordType; 

// ...  
$builder->add('password', RepeatedType::class, array( 
   'type' => PasswordType::class, 
   'invalid_message' => 'The password fields must match.', 
   'options' => array('attr' => array('class' => 'password-field')), 
   'required' => true, 
   'first_options'  => array('label' => 'Password'), 
   'second_options' => array('label' => 'Repeat Password'), 
));

This is mainly used to confirm a user's password or email.

ButtonType

A simple clickable button. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\ButtonType; 
// ...  
$builder->add('save', ButtonType::class, array(
   'attr' => array('class' => 'save'), 
));

ResetType

A button that resets all fields to their initial values. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\ResetType; 
// ...  
$builder->add('save', ResetType::class, array( 
   'attr' => array('class' => 'save'), 
));

ChoiceType

A multi-purpose field used to let the user “choose” one or more options. It can be rendered as a select tag, radio buttons, or checkboxes. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\ChoiceType; 
// ...  
$builder->add(‘gender’, ChoiceType::class, array( 
   'choices'  => array( 
      ‘Male’ => true, 
      ‘Female’ => false, 
   ), 
));

SubmitType

The submit button is used to submit the form data. Its syntax is as follows —

use Symfony\Component\Form\Extension\Core\Type\SubmitType; 
// ...  
$builder->add('save', SubmitType::class, array( 
   'attr' => array('class' => 'save'), 
))

Form Helper Functions

Form helper functions are Twig functions that are used to easily build forms in templates.

form_start

Returns an HTML form tag that points to a valid action, route, or URL. Its syntax is as follows —

{{ form_start(form, {'attr': {'id': 'form_person_edit'}}) }} 

form_end

Closes the HTML form tag created with form_start. Its syntax is as follows —

{{ form_end(form) }} 

TextArea

Returns a textarea tag, optionally wrapped with a JavaScript-based rich text editor.

checkbox_tag

Returns an XHTML-compatible input tag with type = “checkbox”. Its syntax is as follows —

echo checkbox_tag('choice[]', 1);  
echo checkbox_tag('choice[]', 2);  
echo checkbox_tag('choice[]', 3);  
echo checkbox_tag('choice[]', 4); 

input_password_tag

Returns an XHTML-compatible input tag with type = “password”. Its syntax is as follows —

echo input_password_tag('password');  
echo input_password_tag('password_confirm');

input_tag

Returns an XHTML-compatible input tag with type = “text”. Its syntax is as follows —

echo input_tag('name'); 

label_tag

Returns a label tag with the specified parameter.

radiobutton_tag

Returns an XHTML-compatible input tag with type = “radio”. Its syntax is as follows —

echo ' Yes '.radiobutton_tag(‘true’, 1);  
echo ' No '.radiobutton_tag(‘false’, 0); 

reset_tag

Returns an XHTML-compatible input tag with type = “reset”. Its syntax is as follows —

echo reset_tag('Start Over'); 

select_tag

Returns a select tag populated with all the countries of the world. Its syntax is as follows —

echo select_tag(
   'url', options_for_select($url_list), 
   array('onChange' => 'Javascript:this.form.submit();')); 

submit_tag

Returns an XHTML-compatible input tag with type = “submit”. Its syntax is as follows —

echo submit_tag('Update Record');  

In the next section, we will learn how to create a form using form fields.

Student Form

Let us create a simple student details form using Symfony form fields. To do this, we must follow these steps —

Step 1: Create a Symfony Application

Create a Symfony application, formsample , using the following command.

symfony new formsample

Entities are usually created in the “src / AppBundle / Entity /” directory.

Step 2: Create an Entity

Create the file “StudentForm.php” in the “src / AppBundle / Entity /” directory. Add the following changes to the file.

StudentForm.php

studentName; 
   }  
   public function setStudentName($studentName) { 
      $this->studentName = $studentName; 
   }  
   public function getStudentId() { 
      return $this->studentId; 
   }  
   public function setStudentId($studentid) { 
      $this->studentid = $studentid; 
   }
   public function getAddress() { 
      return $this->address; 
   }  
   public function setAddress($address) { 
      $this->address = $address; 
   }  
   public function getEmail() { 
      return $this->email; 
   }  
   public function setEmail($email) { 
      $this->email = $email; 
   }  
   public function getMarks() { 
      return $this->marks; 
   }  
   public function setMarks($marks) { 
      $this->marks = $marks; 
   } 
}     

Step 3: Add StudentController

Go to the “src / AppBundle / Controller” directory, create the file “StudentController.php” and add the following code to it.

StudentController.php

createFormBuilder($stud) 
         ->add('studentName', TextType::class)
         ->add('studentId', TextType::class) 
         ->add('password', RepeatedType::class, array( 
            'type' => PasswordType::class, 
            'invalid_message' => 'The password fields 
            must match.', 'options' => array('attr' => array('class' => 'password-field')), 
            'required' => true, 'first_options'  => array('label' => 'Password'), 
            'second_options' => array('label' => 'Re-enter'), 
         )) 
         
         ->add('address', TextareaType::class) 
         ->add('joined', DateType::class, array( 
               'widget' => 'choice', 
         )) 
            
         ->add('gender', ChoiceType::class, array( 
            'choices'  => array( 
               'Male' => true, 
               'Female' => false, 
            ), 
         )) 
         
         ->add('email', EmailType::class) 
         ->add('marks', PercentType::class) 
         ->add('sports', CheckboxType::class, array( 
            'label'    => 'Are you interested in sports?', 'required' => false, 
         )) 
         
         ->add('save', SubmitType::class, array('label' => 'Submit')) 
         ->getForm();  
         return $this->render('student/new.html.twig', array( 
            'form' => $form->createView(), 
         )); 
   } 
}              

Step 4: Render the View

Go to the “app / Resources / views / student /” directory, create the file “new.html.twig” and add the following changes to it.

{% extends 'base.html.twig' %} 
{% block stylesheets %} 
 

{% endblock %}  
   {% block body %} 
   

Student details:

{{ form_start(form) }} {{ form_widget(form) }} {{ form_end(form) }}
{% endblock %}

Now request the URL “http: // localhost: 8000 / student / new”, and it will produce the following result.

Result

Symfony - an overview of its features with examples

Symfony — Validation

Validation is one of the most important aspects of application development. It validates incoming data. This chapter describes form validation in detail.

Validation Constraints

The validator is designed to validate objects against constraints. If you want to validate an object, simply map one or more constraints to its class, and then pass it to the validation service. By default, when an object is validated, all the constraints of the corresponding class are checked to see whether they actually pass. Symfony supports the following well-known validation constraints.

NotBlank

Validates that a property is not blank. Its syntax is as follows —

namespace AppBundle\Entity; 
use Symfony\Component\Validator\Constraints as Assert; 

class Student { 
   /** 
      * @Assert\NotBlank() 
   */ 
   protected $studentName; 
} 

This NotBlank constraint ensures that the studentName property must not be blank.

NotNull

Validates that a value is not strictly equal to null. Its syntax is as follows —

namespace AppBundle\Entity; 
use Symfony\Component\Validator\Constraints as Assert; 

class Student { 
   /** 
      * @Assert\NotNull() 
   */ 
   protected $studentName; 
} 

Email

Validates that a value is a valid email address. Its syntax is as follows —

namespace AppBundle\Entity; 
use Symfony\Component\Validator\Constraints as Assert; 

class Student { 
   /** 
      * @Assert\Email( 
         * message = "The email '{{ value }}' is not a valid email.", 
         * checkMX = true 
      * ) 
   */ 
   protected $email; 
}

IsNull

Validates that a value is exactly equal to null. Its syntax is as follows —

namespace AppBundle\Entity; 
use Symfony\Component\Validator\Constraints as Assert; 

class Student { 
   /** 
      *

продолжение следует...

Продолжение:


Часть 1 Symfony - an overview of its features with examples
Часть 2 Controller - Symfony - an overview of its features with
Часть 3 Validation Example - Symfony - an overview of its features
Часть 4 Step 1: Create the Project - Symfony - an overview

created: 2020-10-11
updated: 2026-03-10
788



Was this answer useful?
Choose a quick rating so we can improve the next answer for you.
How satisfied are you?


Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Famworks"

Terms: Famworks