0% found this document useful (0 votes)
12 views12 pages

Created by

The document provides instructions for common Symfony tasks like creating a new project, generating entities and repositories, setting up relationships between entities, and performing CRUD operations. It includes examples of creating a basic controller to handle form submission and database persistence, building a form with Twig, and making queries to retrieve and filter entity records.

Uploaded by

yossra Tlili
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views12 pages

Created by

The document provides instructions for common Symfony tasks like creating a new project, generating entities and repositories, setting up relationships between entities, and performing CRUD operations. It includes examples of creating a basic controller to handle form submission and database persistence, building a form with Twig, and making queries to retrieve and filter entity records.

Uploaded by

yossra Tlili
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

//Created by: Jihed Bouazizi

//Creating a project

symfony new FirstProject --version=5.4 --webapp

composer require doctrine/annotations

//Starting & Shuting down a server

symfony server:start

symfony server:stop

//Creating a controller

symfony console make:controller ServiceController

/*Doctrine & Database

To create a databse first you need to modify .env with the root and the database name

you chose. Example: Library 5 is the database name */

DATABASE_URL="mysql://root@localhost/library5"

//Then creating the databse in xampp

symfony console doctrine:database:create

//First migration command

symfony console make:migration

//Updating the database command

symfony console doctrine:migrations:migrate

//Canceling the last update

symfony console doctrine:migrations:migrate prev

//Entity
//Creating & Updating Entity

symfony console make:entity

/*The entity Repository will be generated automatically

in src/Repository*/

//Form

//Creating a form

symfony console make:form FormName

//More about the form down bellow

//CRUD

//Your Controller MUST contain these Uses:

use Doctrine\Persistence\ManagerRegistry;

use Symfony\Component\HttpFoundation\Request;

use App\Form\FORM_NAME;

use App\Entity\ENTITY_NAME;

use App\Repository\REPOSITORY_NAME;

/*For this example we're using the author workshop

Link: https://drive.google.com/file/d/1cYB47k98BxEydHVTlXbdjQUd3e7_lFCl/view

*/

//Creating

/*Parameters

@ Route path: /author/form <

@ Route name: author_add

@ Class/Entity name: Author

@ Reading page: author_show

@ Form path: templates/author/form.html.twig

@ Form Name: formA


*/

#[Route('/author/form', name: 'author_add')]

public function AddAuthor(ManagerRegistry $doctrine, Request $request): Response

$author =new Author();

$form=$this->createForm(AuthorFormType::class,$author);

$form->handleRequest($request);

if($form->isSubmitted()){

$em= $doctrine->getManager();

$em->persist($author);

$em->flush();

return $this-> redirectToRoute('author_show');

return $this->render('author/form.html.twig',[

'formA'=>$form->createView(),

]);

/*Taking the formA variable and using it to make the form

Form path: templates/author/form.html.twig*/

{{form_start(formA)}}

{{form_label(formA.email,"Your e-mail:")}}

{{form_widget(formA.email)}}

{{form_label(formA.Username,"Your Username:")}}

{{form_widget(formA.Username)}}

{{form_label(formA.age,"Your Age:")}}

{{form_widget(formA.age)}}

{{form_end(formA)}}
//---------------------------------------------//

/*Reading

Parameters

@ Route path: /author/show

@ Route name: author_show

@ Class/Entity name: Author

@ Reading page: author_show

@ List path: templates/author/authorlist.html.twig

*/

#[Route('/author/show', name: 'author_show')]

public function show(AuthorRepository $rep): Response

$authors = $rep->findAll();

return $this->render('author/authorlist.html.twig', ['authors'=>$authors]);

}
/*List path: templates/author/authorlist.html.twig

The list will use a For loop to list the authors plus showing the update & delete

button following these 2 lines:

<a href ="{{path('author_update',{'id':author.id})}}">Update</a>

<a href ="{{path('author_delete',{'id':author.id})}}">Delete</a>

NOTE: Use the path names and not the routes (author_delete/author_update)

which will redirect us to either deleting or updating the author.

An add button will also be added with the following line in case you wanted to insert

another author.

<a href ="{{path('author_add')}}">Add</a>

*/

{% block body %}

<h1>Liste des Auteurs</h1>

<table>

<thead>

<tr>

<th>Nom d utilisateur</th>

<th>Email</th>

<th>Actions</th>

</tr>

</thead>

<tbody>

{% for author in authors %}

<tr>

<td>{{ author.username }}</td>

<td>{{ author.email }}</td>

<td>

<a href ="{{path('author_update',{'id':author.id})}}">Update</a> |

<a href ="{{path('author_delete',{'id':author.id})}}">Delete</a>

</td>
</tr>

{% endfor %}

</tbody>

</table>

<a href ="{{path('author_add')}}">Add</a>

{% endblock %}

//---------------------------------------------//

/*Updating

Parameters

@ Route path: /author/update/{id}

@ Route name: author_update

@ Class/Entity name: Author

@ Reading page: author_show

@ Form path: templates/author/form.html.twig

@ Form Name: formA

*/

/* Updating needs an ID, putting the one you need to update in {id} will automatically

Create the form and fill it with the retrieved data, all you need to do is changing
whatever you want and pressing the update button*/

#[Route('/author/update/{id}', name: 'author_update')]

public function UpdateAuthor(ManagerRegistry $doctrine, Request $request, AuthorRepository


$rep, $id): Response

$author = $rep->find($id);

$form=$this->createForm(AuthorFormType::class,$author);

$form->handleRequest($request);

if($form->isSubmitted()){

$em= $doctrine->getManager();

$em->persist($author);

$em->flush();

return $this-> redirectToRoute('author_show');

return $this->render('author/form.html.twig',[

'formA'=>$form->createView(),

]);

/*Update path: templates/author/form.html.twig

Same form as adding

*/

//---------------------------------------------//

/*Deleting

Parameters

@ Route path: /author/delete/{id}

@ Route name: author_delete

@ Class/Entity name: Author

@ Reading page: author_show


*/

#[Route('/author/delete/{id}', name: 'author_delete')]

public function deleteAuthor($id, AuthorRepository $rep, ManagerRegistry $doctrine): Response

$em= $doctrine->getManager();

$author= $rep->find($id);

$em->remove($author);

$em->flush();

return $this-> redirectToRoute('author_show');

/*The delete methode is the same as updating but without a form taking the {id}

and directly deleting using:

$em->remove($author);

then automatically redirecting you to the authors list.

*/

//Drop Down list

//start with adding

use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

//Then add this to the builder

->add('Type', ChoiceType::class, [

'label' => 'Your Type:',

'choices' => [

'Annual Flower' => 'Option 1',

'Perennial Flowers' => 'Option 2',

'Flowering shurbs' => 'Option 3',

// Add more options as needed

],

])
/* NOTES TO TAKE:

In the AuthorFormType.php you MUST add

use Symfony\Component\Form\Extension\Core\Type\SubmitType;

->add('Add',SubmitType::class)

in order to show the "add" action button to make the form work

*/

/////////////////////////////////Part 2//////////////////////////////////////////

//Relationships:

/*OneToMany:

Taking the Author/Book Workshop:

https://drive.google.com/file/d/1JhSEBWsOgg24VQ5arlAARszItXBky2VZ/view

For the exemple one author got Many books

*/

//For the Author Entity:

#[ORM\OneToMany(mappedBy: 'author', targetEntity: Book::class, orphanRemoval: true)]

private Collection $books;

//For the Book Entity:

#[ORM\ManyToOne(targetEntity: Author::class, inversedBy: "books")]

#[ORM\JoinColumn(nullable: true)]

private ?Author $author;

//Or Using the

symfony console make:entity


//Query (Requête)

//Simple query to get the whole list sorted by an attribute

//For this query we're getting the "Joueur List" Sorted by the "Nom"

//ASC or DESC for ascendant or descendant ML AKBER LL ASGHER (DESC)

#[Route('/joueur/list', name: 'list_joueur')]

public function listJoueur(JoueurRepository $joueurRepository)


{

$joueurs = $joueurRepository->findBy(array(),array('nom'=>'ASC'));

return $this->render('joueur/index.html.twig', ['joueurs' =>$joueurs]);

//SEARCH

//Query to search for one or two or more attributes

//In the Entity Repository we have:

public function show($parameter1,$parameter2)

return $this->createQueryBuilder('s')

//The Attribute MUST have the same name as in the Database

->where('s.attribute1 LIKE :parameter1')

->andWhere('s.attribute2 LIKE :parameter2')

->setParameter('parameter1', $parameter1)

->setParameter('parameter2',$parameter2)

->getQuery()

->getResult()

//Controller

#[Route('/joueur/list', name: 'list_joueur')]

public function showBytwoparameters(JoueurRepository $joueurRepository)

$joueurs = $joueurRepository->show($parameter1, $parameter2);

return $this->render('joueur/index.html.twig', ['joueurs' =>$joueurs]);

//Twig

<form action="{{path('list_joueur')}}">
<input type="text" name="parameter1">

<input type="text" name="parameter2">

<input type="submit" value="Search">

</form>

<table border=2>

<tr>

<td>Id</td>

<td>parameter1</td>

<td>parameter2</td>

</tr>

{% for joueur in joueurs %}

<tr>

<td>{{joueur.id}}</td>

<td>{{joueur.parameter1}}</td>

<td>{{joueur.parameter2}}</td>

</tr>

{% endfor %}

</table>

You might also like