Symfony Cheatsheet
What this page covers
Console commands
Cache clearing, bundle and CRUD generation, container and router debugging — written as app/console, which is bin/console from Symfony 3 onward.
Sessions and the flash bag
Setting, reading and clearing flash messages, and where the session service lives.
Forms
Building form types, handling submission and rendering the result in Twig.
Doctrine DBAL and ORM
Mapping imports, entity generation, and the schema commands that go with them.
This page documents Symfony 2.x and is kept for reference. It was
written when app/console was the command, and it still draws visitors
searching for those commands — which is the only reason it is still here.
If you are working on anything current, the
Symfony 7 cheat sheet is the one you want.
Symfony 3 moved app/console to bin/console and every version since has
kept it there, so if you are on Symfony 3 or later, read every
app/console below as bin/console. Run them from the project root as
the web user — not as root, which leaves files the web server cannot
write.
For a current dependency list, use composer create-project symfony/skeleton
rather than a copied composer.json — the pinned Symfony 2.x list this
used to link to has not been accurate for a decade.
To clear the cache for dev environment, omit the “–env=prod” option, which clears the production environment cache.
$ app/console cache:clear --env=prod
Make a new bundle skeleton. Navigate to your Symfony project first. “Acme” is always the demo, so replace with your own bundle namespace.
$ app/console generate:bundle --namespace=Acme/Bundle/BlogBundle
Generate CRUD forms, (Create, Read, Update & Destroy) automatically. Leaving out options will bring up a list of questions before creating the CRUD forms:
$ app/console doctrine:generate:crud
Get current route. What’s a route?!
$request = $this->container->get('request');
$routeName = $request->get('_route');
You can find the class used as the provider-service using:
$ app/console container:debug --show-private your_provider_service
List all registered routes:
$ app/console router:debug
Dump assets to production environment:
$ bin/console assetic:dump
Please note above: Just checking if you are paying attention! The new Symfony folder structure is coming and the console will be in the “/bin” folder in the future.
To generate entities from an existing database in Symfony, you first need Doctrine to introspect the database, then generate the entities. Be careful, your database relationships will probably need to be tweaked, getting your Doctrine table relationships mapped correctly is very important and might be a bit time consuming until you get a handle on it!
$ php app/console doctrine:mapping:import --force AcmeBlogBundle yml
$ php app/console doctrine:generate:entities AcmeBlogBundle
Note above: I despise annotations in my code, I ALWAYS use YML files.
Get more information about current Doctrine entity mappings:
$ app/console doctrine:mapping:info
Redirect to a URL from a controller without a route:
return $this->redirect("/dash"); exit;
Accessing unmapped form fields from controller:
$unmappedField = $form['unmapped_field']->getData();
//Accessing the User Object within a controller class:
$user=$this->getUser();
$userId=$user->getId();
// Be sure to "use" the following:
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Model\UserInterface;
Since we’re on the FOS User Bundle, here’s a way to add a new user and change that user’s password. Shell command through Putty on the command line. Change the “admin” user’s password:
$ app/console fos:user:change-password admin <new-password>
Symfony Session variables, “flash bag”
{% if app.session.flashbag.has('message') %}
{{ app.session.flashbag.get('message').0 }}<br/>
{% endif %}
By Symfony 2.6, flashbag is an array so you may need to iterate with foreach.
The above example accesses only the first element, hence the 0 (zero) index.
Symfony Forms
The best, easy-to-follow example of how to persist multiple related entities upon form submission with Doctrine. This is a sample controller action. Thanks to users from Stack Overflow:
public function testAction(Request $request) {
$em = $this->getDoctrine()->getEntityManager();
$basket = new Basket();
$basket->addItem(new BasketItem());
$basket->addItem(new BasketItem());
$em->persist($basket);
try {
$em->flush();
} catch(Exception $e) {
die('ERROR: '.$e->getMessage());
}
die ('end');
}
Know if page was reached via POST:
$request->isMethod('POST');
Get current URL of script:
$currentUrl = $this->getRequest()->getUri();
If you like to let Symfony create CRUD for your database tables, you might freeze up the computer if you access the “index” action since this will list all records of the table by default to the browser all at once. Here’s a way to set limits from repository queries:
$product = $repository->findBy(
array('field1' => 'searchCriteria'),
array('field2' => 'moreCriteria'),
$myLimit,
$myOffset
);
Troubleshooting form submissions. This method is being replaced, but still works for Symfony 2.5!
if ($editForm->isSubmitted()){
var_dump($editForm->getErrorsAsString()); exit;
}
Symfony Doctrine DBAL & ORM
Get Doctrine var_dump debug output in your controller:
exit(\Doctrine\Common\Util\Debug::dump($yourObjectToDebug));
Other useful snippets:
To install Braincrafted Bootstrap for Symfony, see the bundle on GitHub. It is no longer maintained, and its old documentation site is now a parked domain advertising itself for sale, so do not follow that address.
CDN to Bootstrap.
Versions will probably have changed, but these are lts stable versions:
Stylesheet: //maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css
Script: //maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js
Quick shell commands that I seem to forget for some reason. Find a “directory” named “node_modules” for instance. “-type d” means “Directory”, change to “-type f” for file instead:
find / -name node_modules -type d
– Aaron Belchamber