Symfony 5 Cheat Sheet
by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/
Entity Manager in a controller Doctrine Query (cont)
$this->getDoctrine()->getManager(); Get default entity Cache::MODE_REFRESH no read, only refresh
manager setCacheable($trueFalse) Enable/disable result caching
$this->getDoctrine()->getManagerForClas‐ Get entity specific
s(MyEntity::class) manager Magic repository functions
find ($id) Returns one entity
Repositories in a controller
findOneBy($criteria, $orderBy) Returns one entity
$this->getDoctrine()->getRepository(MyEntity::class);
findBy ($criteria, $orderBy, $limit, $offset) Returns collection
$criteria = ['field' => 'value'] Single field / value
Doctrine Query
$criteria = ['field' => ['value1', 'value2']] Single where-in
getResult($hydrationMode = Retrieve a collection
self::HYDRATE_OBJECT) $criteria = ['field1' => 'value', 'field2' => multiple fields /
'value2'] values
getSingleResult($hydrationMode Retrieve a single result or
= null) exception $repository = $this->getDoctrine()->getRepository(Product::class);
$product = $repository->findOneBy(['name' => 'Keyboard']);
getOneOrNullResult($hydrati‐ Retrieve a result or NULL
onMode = null)
Doctrine criteria - filtering collections
getArrayResult () Retrieve an array
where($Expression) Replaces previous statement
getScalarResult() Retrieves a flat/rectangular
result set of scalar values [and/or]Where($Expression) Adds AND /OR where statement
getSingleScalarResult() Retrieves a single scalar value orderBy($array) Sets OrderBy
or exception setFirstResult($firstResult) Sets first result
AbstractQuery::HYDRATE_O‐ Object graph default setMaxResult($max) Sets Maximum results
BJECT
$userCollection = $group->getUsers();
AbstractQuery::HYDRAT‐ Array graph
E_ARRAY $criteria = Criteria::create()
AbstractQuery::HYDRATE_S‐ Flat rectangular result with ->where(Criteria::expr()->eq("birthday", "1982-02-17"))
CALAR scalars ->orderBy(array("username" => Criteria::ASC))
->setFirstResult(0)
AbstractQuery::HYDRATE_S‐ Single scalar value
->setMaxResults(20)
INGLE_SCALAR
;
AbstractQuery::HYDRATE_S‐ Very simple object fast
$birthdayUsers = $userCollection->matching($criteria);
IMPLEOBJECT
setCacheMode($cacheMode)
Cache::MODE_GET may read, not write
Cache::MODE_PUT no read, write all
Cache::MODE_NORMAL read and write
By Marcel Berteler (pluk77) Published 18th April, 2023. Sponsored by Readable.com
cheatography.com/pluk77/ Last updated 10th May, 2023. Measure your website readability!
Page 1 of 6. https://readable.com
Symfony 5 Cheat Sheet
by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/
Doctrine ExpressionBuilder and Expr Doctrine Query Builder (cont)
andX ($arg1, $arg2, ...) Multiple arguments AND add($dqlPartName, $dqlPart, $append = false)
orX($arg1, $arg2, ...) Multiple arguments OR $dqlPartName: select, from, join, set, where, groupBy, having,
[n]eq($field, $value) [Not] Equal orderBy
gte Greater than [or equal] Wrappers for add():
lte Less than [or equal] [add]select($select= null)
isNull($field) Is Null delete($delete = null, $alias = null)
[not]in ($field, array $values) [not] In update ($update = null, $alias = null)
memberOf($field, $value) ExpressionBuilder only Member of set ($key, $value)
isMemberOf($field, $value) Expr only Member of from($from, $alias, $indexBy = null)
isNotNull($field) Expr only Is not Null [inner/left]join($join, $alias, $conditionType = null, $condition = null,
$indexBy = null)
between ($field, $x, $y) Expr only Between $x and $y
[and/or]where($where)
trim($field) Expr only Trim
[add]groupBy($groupBy)
concat($x, $y) Expr only Concat
[and/or]having($having)
literal($string) Expr only Literal
[add]orderBy($field, $order = null)
lower($field) Expr only Lower case
upper($field) Expr only Upper case
Doctrine raw SQL
count($field) Expr only count
$Connection= $EntityManager->getCon‐ Get connection
# Doctrine Expr # nection(): Connection;
Criteria::expr()->orX(
$Statement = $Connection- Prepare statement
Criteria::expr()->eq('id', $facilityId),
>prepare(string $sql): Statement; from string
Criteria::expr()->eq('active', TRUE)
$Statement->bindValue(string|int $param, Bind a value to a
);
$value, $type = null): bool corresponding name
# Doctrine ExpressionBuilder # $Statement->execute(?array $params = Execute the statement
$qb = $this->createQueryBuilder('f'); null): bool
$Statement->fetchAll(int $fetchStyle = Fetch all results
$qb->where($qb->expr()->eq('id', '?arg1')) PDO::FETCH_BOTH): array
->setParameter('arg1', $facilityId); $Statement->fetchOne (int $fetchStyle = Fetch single result
PDO::FETCH_BOTH): array
$qb->select($qb->expr()->substring('o.orderNumber', 4, 3));
$Statement->rowCount(): int Return the number of
rows
$qb->select($qb->expr()->concat('p1.surname', $qb->expr()->liter‐
al(','), 'p1.firstName');
Doctrine Query Builder
setParameter($parameter, $value)
addCriteria(Criteria $criteria)
[get/set]MaxResults($maxResults)
[get/set]FirstResult($firstResult)
getQuery()
By Marcel Berteler (pluk77) Published 18th April, 2023. Sponsored by Readable.com
cheatography.com/pluk77/ Last updated 10th May, 2023. Measure your website readability!
Page 2 of 6. https://readable.com
Symfony 5 Cheat Sheet
by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/
Doctrine raw SQL (cont) Authorization in a controller (cont)
$Statement->free(): void Free stored result memory if (false === $authChecker->isGranted('ROLE_ADMIN')) {
throw new AccessDeniedException('Unable to access this page!');
$connection = $entityManager->getConnection();
}
// ...
$sql = 'SELECT * FROM events WHERE start_date >= :startdate';
}
# Example of using annotation #
$statement = $conn->prepare($sql);
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
$statement->bindValue('startdate', $startDate->format('Y-m-d H:i:s'));
/**
$statement->execute();
* @Security("has_role('ROLE_ADMIN')")
*/
return $statement->fetchAll();
public function hello($name)
{
Authorization
// ...
IS_AUTHENTICATE‐ User has successfully authenticated, not
}
D_FULLY via 'remember me cookie'
IS_AUTHENTICATE‐ All logged in users Persisting Entities
D_REMEMBERED
// get the entity manager that manages this entity
IS_REMEMBERED Only users authenticated using the $em = $this->getDoctrine()->
remember me functionality getManagerForClass(MyEntity::class);
IS_IMPERSONATOR When the current user is impersonating // create a new entity
another user in this session $entity = new MyEntity();
// populate / alter properties
All roles you assign to a user must begin with the ROLE_ prefix in
$entity->setName('Default Entity');
order for the default symfony RoleVoter to vote. Other prefixes
// tell Doctrine you want to (eventually) save
require a custom voter.
$em->persist($entity);
// actually executes the queries
Authorization in a controller
$em->flush();
# Example of using wrapper #
public function hello($name)
Authorization via security.yaml
{
# config/packages/security.yaml
// The second parameter is used to specify on what object the role is
security:
tested.
access_control:
$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to
# public access only for /
access this page!');
// ...
}
# Example of using AuthorizationChecker
use Symfony\Component\Security\Core\Authorization\Authorizati‐
onCheckerInterface
use Symfony\Component\Security\Core\Exception\AccessDenied‐
Exception;
public function hello($name, AuthorizationCheckerInterface $authC‐
hecker)
{
By Marcel Berteler (pluk77) Published 18th April, 2023. Sponsored by Readable.com
cheatography.com/pluk77/ Last updated 10th May, 2023. Measure your website readability!
Page 3 of 6. https://readable.com
Symfony 5 Cheat Sheet
by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/
Authorization via security.yaml (cont) Create a form from a class in a controller
- { path: ^/$, roles: PUBLIC_ACCESS } # Create a form from a form class with a default name #
# public access to login page /login $form = $this->createForm(TaskForm::class, $data, array(
- { path: ^/login, roles: PUBLIC_ACCESS } 'action' => $this->generateUrl('target_route'),
# or require ROLE_ADMIN or ROLE_USER_ADMIN for 'method' => 'GET',
/admin/users* ));
- { path: '^/admin/users', roles: [ROLE_USER_ADMIN, ROLE_A‐ # Create a form from a form class with a non-default name #
DMIN] } $form = $this->container->get('form.factory')
# require ROLE_ADMIN for /admin* ->createNamed('form1', TaskForm::class, $data, array(
- { path: ^/admin, roles: ROLE_ADMIN } 'action' => $this->generateUrl('target_route'),
# authenticated users only to the rest /* 'method' => 'GET',
- { path: ^/, roles: IS_AUTHENTICATED_FULLY ));
No limit on amount of URL patterns. Each is a regular expression.
Form Options
First match will be used.
'action' => '' Where to send the form's data
Prepend the path with ^ to ensure only URLs beginning with the on submission (usually a URI)
pattern are matched. 'allow_extra_fields ' => false Allow additional fields to be
submitted
Authorization in template
'error_mapping' => array('match‐ Modify the target of a validation
{% if is_granted('ROLE_ADMIN') %} ingCityAndZipCode' => 'city') error
<a href="...">Delete</a>
'extra_fields_message ' => 'This Validation error message if
{% endif %}
form should not contain extra additional fields are submitted
fields.'
Create a new form in a controller
'inherit_data' => false Inhered data from parent form
# Create a new form with a default name # or not
$form = $this->createFormBuilder($data)
'method ' => 'POST' HTTP method used to submit
->add('dueDate', null, array(
the form
'widget' => 'single_text'))
'post_max_size_message' => 'The Validation message for size of
->add('save', SubmitType::class)
uploaded file was too large.' post form data
->getForm();
# Create a form with a non-default name #
$form = $this->container->get('form.factory')
->createNamedBuilder(
'form1', FormType::class, $data)
->add('dueDate', null, array(
'widget' => 'single_text'))
->add('save', SubmitType::class)
->getForm();
By Marcel Berteler (pluk77) Published 18th April, 2023. Sponsored by Readable.com
cheatography.com/pluk77/ Last updated 10th May, 2023. Measure your website readability!
Page 4 of 6. https://readable.com
Symfony 5 Cheat Sheet
by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/
Form Options (cont) Console
'validation_groups ' => Disable the Validation of Submitted bin\console List available commands and show the
false Data Symfony version
public function configureOptions(OptionsResolver $resolver) { server:run Run the built-in web server
$resolver->setDefaults(array( assets:install -- Install bundle assets as a symlink or hardcopy
# Options go here # symlink
));
debug:autowire Lists classes/interfaces you can use for
}
autowiring
debug:config Dumps the current configuration for an
Log Levels / Console Verbosity (OutputInterface)
extension
emerge‐ System is unusable.
debug:container Displays current services for an application
ncy()
debug:form Lists classes/interfaces you can use for
alert() Action must be taken immediately.
autowiring
critical() Critical conditions.
debug:route Displays current routes for an application
error() Runtime errors that do not VERBOS‐ -q /
require immediate action but ITY_QUIET stderr
Usage:
should typically be logged and (-1)
php bin\console command [options] [arguments]
monitored.
warning() Exceptional occurrences that are VERBOS‐ (non)
Options:
not errors. ITY‐ /
-h, --help Display this help message
_NORMAL stdout
-q, --quiet Do not output any message
(0)
-n, --no-interaction Do not ask any interactive question
notice() Normal but significant events. VERBOS‐ -v -e, --env=ENV The environment name [default: "dev"]
ITY_VE‐ --no-debug Switches off debug mode
RBOSE (1) -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for
info() Interesting events. VERBOS‐ -vv normal output, 2 for more verbose output and 3 for debug
ITY_VE‐
RY_‐ Basic form
VERBOSE class TaskForm extends AbstractType
(2) {
debug() Detailed debug information. VERBOS‐ -vvv public function buildForm(
ITY‐ FormBuilderInterface $builder,
_DEBUG array $options)
(3) {
$builder
use Psr\Log\LoggerInterface;
->add('dueDate', DateType::class, array(
'widget' => 'single_text',
public function index(LoggerInterface $logger) {
$logger->info('I just got the logger');
}
By Marcel Berteler (pluk77) Published 18th April, 2023. Sponsored by Readable.com
cheatography.com/pluk77/ Last updated 10th May, 2023. Measure your website readability!
Page 5 of 6. https://readable.com
Symfony 5 Cheat Sheet
by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/
Basic form (cont) TwigBridge - Forms (cont)
'label' => 'Due Date', {{ form_errors (view.field) }} Render field error
'required' => false, {{ form_widget(view.field, variables) }} Render field widget
'attr' => array('maxlength' => 10),
{# render a label, but display 'Your Name' and add a "foo" class to it
'constraints' => array(new Length(
#}
array('max' => 10)))
{{ form_label(form.name, 'Your Name', {'label_attr': {'class': 'foo'}}) }}
))
->add('save', SubmitType::class);
{# render a widget, but add a "foo" class to it #}
}
{{ form_widget(form.name, {'attr': {'class': 'foo'}}) }}
public function configureOptions(
OptionsResolver $resolver)
{# render a field row, but display a label with text "foo" #}
{
{{ form_row(form.name, {'label': 'foo'}) }}
$resolver->setDefaults(array(
'method' => 'GET',
Response from a controller
));
} render($view, $parameters, $response = null) Render the template
} and return a
Response
TwigBridge - Forms json($data, $status = 200, $headers = array(), Encode data and
{{ form(view, variables) }} Render whole form $context = array()) return a Json
response
{{ form_start(view, variables) }} Render start tag
file($file, $fileName = null, $disposition = Return a file
{{ form_errors (view) }} Render global errors
ResponseHeaderBag::DISPOSITION_AT‐ response
{{ form_row(view, variables) }} Render all the fields
TACHMENT)
{{ form_rest(view, variables) }} Render all other fields
redirectToRoute($route, $parameters = Redirect to route
{{ form_end(view, variables) }} Render end tag + array(), $status = 302)
all other fields
redirect ($url, $status = 302) Redirect to external
{{ form_row(view.field) }} Render field label, error URL
and widget
forward ($controller, $path = array(), $query = Forwards the
{{ form_label (view.field, label, variables) }} Render field label array()) request to another
controller
return $this->render('admin/post/show.html.twig', [
'post' => $post,
'delete_form' => $deleteForm->createView(),
]);
return $this->json($data);
By Marcel Berteler (pluk77) Published 18th April, 2023. Sponsored by Readable.com
cheatography.com/pluk77/ Last updated 10th May, 2023. Measure your website readability!
Page 6 of 6. https://readable.com