Skip to content

Instantly share code, notes, and snippets.

@rmpel
Last active June 5, 2019 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmpel/4bc982d1840e34f23b4fa7e214eecff9 to your computer and use it in GitHub Desktop.
Save rmpel/4bc982d1840e34f23b4fa7e214eecff9 to your computer and use it in GitHub Desktop.
Symfony 4 cheatsheet

Symfony 4 cheatsheet

terms

  1. Entity - a thing to store in the database
  2. Repository - handles the entities
  3. Service - A tool or set of tools (like a Mailer or an API Library)
  4. Route - Links a URL to code
  5. Controller - The above code resides herein; routes that belong to eachother like lists for entities and CRUD for those entities are bundled in their own controller.
  6. View - How is the data presented to the user. This can be ANYTHING! HTML, XML, JSON, a File Download etc.

console

The console is found in the root of the project (root)/bin/console. Older versions had (root)/symfony to do the same. On Windows use php bin/console, while on Mac or Linux use ./bin/console.

command purpose
make:entity Create a new entity, or add fields to an existing entity
make:entity --regenerate Add missing getters & setters
make:entity --regenerate --overwrite REWRITE ALL getters & setters - your changes to the existing getters/setters is lost
make:form Generate form code. When created, use as demonstrated in example 3
make:controller Create a new controller
make:command Create a new CLI-controller
make:migration Process changes to entities and put them in a migration file
doctrine:migrations:migrate Actually make the changes in the database
doctrine:schema:update --force Re-do the database structure based on the current state of all entities

Example 1: Loading an entity

# Example entity: \App\Entity\Book .
use App\Entity\Book;

class BooksController extends AbstractController {
    /**
     * @route("/book/{book_id}", name="read_book")
     */
    public function readBook($book_id) {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->getRepository(Book::class)->find($book_id);
    }
}
Repository method Effect
find(id) Retrieve by ID
findAll Tablescan
findBy(criteria, order, limit, offset) Find filtered
findOneBy(criteria) Find filtered, return one!
EntityManager method Effect
persist(Entity) Mark for saving, often this is already done by find* methods
flush() clear cache???? effect is actually saving the data to the database

Example 2: Saving an entity

# Example entity: \App\Entity\Book .
use App\Entity\Book;

class BooksController extends AbstractController {
    /**
     * @route("/book/{book_id}/mark-read", name="mark_book_read")
     */
    public function markBookRead($book_id) {
        $entityManager = $this->getDoctrine()->getManager();
        $bookRepository = $entityManager->getRepository(Book::class); // do not type '\App\Entity\Book'. You should be able to guess why.
        $book = $bookRepository->find($book_id);
        $book->setIsRead(true);
        // $book->save(); // symfony 1 method, no longer exists
        $entityManager->persist($book);
        $entityManager->flush();
    }
}

Example 3: using forms, created by ./bin/console make:form

$form  = $this->createForm( TheFormType::class, $anEntity ); // load the form
$form->handleRequest($request); // process a POST
if ( $form->isSubmitted() && $form->isValid() ) { // is actual POST, and validates OK
      $entityManager->persist( $anEntity );
      $entityManager->flush();
}

$html = $form->createView();

Example 4: using forms, created by code

$form  = $this->createFormBuilder( $anEntity )
         ->add( 'title', TextType::class )
         ->add( 'ISBN', TextType::class )
         ->add( 'isRead', CheckboxType::class )
         ->add( 'save', SubmitType::class, [ 'label' => 'Save' ] )
         ->getForm(); ); // load the form
$form->handleRequest($request); // process a POST
if ( $form->isSubmitted() && $form->isValid() ) { // is actual POST, and validates OK
      $entityManager->persist( $anEntity );
      $entityManager->flush();
}

$formObject = $form->createView();
{{ form(formObject) }}{# prints the form #}

Read the Symfony documentation on form_customization.

Form Field Types

FieldType Shows Remarks
BirthdayType Birthday like DateTime, with restrictions
ButtonType Button
CheckboxType Checkbox
ChoiceType Choice What's this?
CollectionType Collection Don't know yet
ColorType Color Color picker
CountryType Country Select with countries
CurrencyType Currency For money input ??
DateIntervalType DateInterval ?
DateTimeType DateTime
DateType Date
EmailType Email
FileType File
FormType Form nested forms??? need to check this out!
HiddenType Hidden
IntegerType Integer
LanguageType Language
LocaleType Locale
MoneyType Money
NumberType Number
PasswordType Password
PercentType Percent
RadioType Radio
RangeType Range
RepeatedType Repeated
ResetType Reset
SearchType Search
SubmitType Submit
TelType Tel
TextType Text
TextareaType Textarea
TimeType Time
TimezoneType Timezone
UrlType Url
Remember You use this with FieldType::class !
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment