Symfony 2 Cheat Sheet

This is a work in progress, feel free to add anything useful in the comments below.

Forms

Stupid form, you go squish now!

Adding Javascript to a Form

For example, to add an onchange event to your drop down box, add the following:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('my_example_dropdown', 'choice', array(
                'choices' => array(
                    'fish' => 'Fish',
                    'chips' => 'Chips'
                ),
                'expanded' => false,
                'multiple' => false,
                'attr' => array( 
                      'class' => 'myFancyCssClassHere',
                      'onchange'  => 'this.form.submit()',
                 ),
            ))
        ;
    }

Entity Management

Please don’t tell me that command just erased all my hard work!?

Remember, unless you specify –no-backup, you can always recover a copy of your entity by finding the “EntityName.php~” file in same directory as your existing entity.

Generating Just One Entity

This is a short How To for generating an entity for a new table you have added to your database.

Important: The filter command requires a camel cased version of your table name. So if your table was called ‘your_table_name’, be sure to use ‘YourTableName’, much like any entity references.

Change annotation to yaml, xml, or whatever you are using.

php app/console doctrine:mapping:convert annotation ./src/Your/BundleName/Resources/config/doctrine --from-database --filter="YourTableName"
php app/console doctrine:mapping:import YourBundleName annotation --filter="YourTableName"
php app/console doctrine:generate:entities YourBundleName:YourTableName --no-backup

You don’t need to take a backup on the last command, as it would create your entity twice.

This is my version of this question from Stack Overflow.

Lifecycle Callbacks

How I do Lifecycle Callbacks (with sample code)

Debugging

Sometimes things get complicated…

Exceptions

A list of all Exceptions in Symfony 2.1.2 (External link)

Doctrine

Helpful for getting a readable var_dump from a Doctrine query:

exit(\Doctrine\Common\Util\Debug::dump($yourDoctrineResult));

Logging

Write to the Symfony log file:

$this->get('logger')->info('Put your helpful debug text here');

Testing

Helpful for identifying what’s actually being seen by your crawler:

var_dump($client->getResponse()->getContent());
exit(var_dump($client->getResponse()->getContent()));

Twig Templates

Don’t bother with Twig’s dump functionality, get the Ladybug Bundle

{{ ladybug_dump(form) }}

Finding your Symfony 2 Version

A nice easy one:

php app/console -V
Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *

This blog is kept spam free by WP-SpamFree.