Code snippets for symfony 1.x


Popular Tags

action admin ajax batch cache cli criteria css culture custom database date debug doctrine email filter form forms generator helper i18n javascript model navigation object pager pagination pake propel query routing session sql symfony template test user validation validator view widget
This is a public source code repository where you can find, rate and comment code snippets published by others, or store you owns and categorize them with tags for easy retrieval.

Latest snippets

Override save() and delete() methods in the admin generator

Sometimes, you want to do something just before or just after saving or deleting an object in the admin generator. To do that, you can override the saveObject() and/or deleteObject() method in your actions.class.php file:

protected function saveCustomer($customer)
  // pre save hook
  // call the parent save() method
  // post save hook

You can also bypass the parent method if you want.

protected function deleteCustomer($customer)
  // save the customer object
  // bypass the deletion by not calling the parent method
by Fabien Potencier on 2006-05-21, tagged admin 

Restrict objects displayed in the admin generator

If you want to restrict the objects displayed in the admin generator, you can add a permanent criteria by overriding the addFiltersCriteria() method:

protected function addFiltersCriteria(&$c)
  $c->add(CustomerPeer::DELETED, false);
by Fabien Potencier on 2006-05-21, tagged admin 

Change session storage

By default, symfony stores user sessions in files.

You can store them in your database by changing your apps/APPNAME/config/factories.yml configuration file:

    class: sfMySQLSessionStorage
      database: propel
      db_table: SESSION_TABLE_NAME

There are several available session storage classes:

The API documentation lists all available configuration parameters.

by Fabien Potencier on 2006-05-21, tagged database  session 
(1 comment)

Use the model in a batch or a test

To use database connections defined in the databases.yml configuration file, you can use the following snippet:

// initialize database manager
$databaseManager = new sfDatabaseManager();
by Fabien Potencier on 2006-05-21, tagged batch  configuration  propel  test 

AJAX vote - 5 stars

In the template where the object that users can vote on (here, a snippet) is displayed, add:

  <?php echo use_helper('Javascript') ?>
  <?php $id = $snippet->getId() ?>
  <?php if($sf_user->canVoteFor($snippet)): ?>
    <span id="vote_for_<?php echo $id ?>" style="white-space:nowrap;">
      rate this snippet: <?php for($i = 1 ; $i <= 5 ; $i++): ?><div class="rate <?php if($i <= $snippet->getAverageVote()): ?>rated<?php endif; ?>" 
      id="vote_<?php echo $id ?>_<?php echo $i ?>"><?php echo link_to_remote(image_tag('spacer.gif', 'width=10 height=10'), array(
        'url'         => 'snippet/voteForSnippet?id='.$id.'&vote='.$i,
        'update'      => 'vote_for_'.$id,
        'loading'     => visual_effect('appear', 'indicator'),
        'complete'    => visual_effect('fade', 'indicator').visual_effect('highlight', 'vote_for_'.$id),
      ), array(
        'onMouseOver' => 'highlight_stars('.$id.', '.$i.', true);',
        'onMouseOut'  => 'highlight_stars('.$id.', '.$i.', false);',  
      )) ?></div><?php endfor; ?>
      <span id="indicator" style="display:none"> <?php echo image_tag('indicator.gif') ?></span>
  <?php else: ?>
    <?php include_partial('voted', array('id' => $id, 'vote' => $snippet->getAverageVote())) ?>
  <?php endif; ?>

Of course, you have to define the rules about who can vote on what in the -&gt;canVoteFor() method of the User object (in apps/myapp/lib/myUser.php). The template uses a _voted.php partial:

<?php for($i = 1 ; $i <= 5 ; $i++): ?><div class="rate <?php if($i <= $vote): ?>rated<?php endif; ?>" id="vote_<?php echo $id ?>_<?php echo $i ?>"><img src="/images/spacer.gif" width="10" height="10" /></div><?php endfor; ?>

DO NOT add extra spaces to the long lines, or the stars get separated by blank spaces.

The mechanism that changes the aspect of stars relies on classes, so add the following styling to a CSS used in your template:

.rate {
background-position: left 10px;
background-position: left 0px;
.ratehover {
background-position: left 20px;

The vote_star.gif file is a 10x30px image containing three versions of the star: voted, hovered, not voted.


The snippet/voteForSnippet action does something like:

  public function executeVoteForSnippet()
    $this->id   = $this->getRequestParameter('id');
    $snippet = SnippetPeer::retrieveByPk($this->id);
      return sfView::NONE;
    $vote = new Vote();
    $this->vote = $vote->getSnippet()->getAverageVote();
by Francois Zaninotto on 2006-05-20, tagged ajax  vote 

Pagination navigation helper

In a template displaying a paginated list, you need to show the pager navigation. Create a PaginationHelper.php in lib/helper:

function pager_navigation($pager, $uri)
  $navigation = '';
  if ($pager->haveToPaginate())
    $uri .= (preg_match('/\?/', $uri) ? '&' : '?').'page=';
    // First and previous page
    if ($pager->getPage() != 1)
      $navigation .= link_to(image_tag('/sf/images/sf_admin/first.png', 'align=absmiddle'), $uri.'1');
      $navigation .= link_to(image_tag('/sf/images/sf_admin/previous.png', 'align=absmiddle'), $uri.$pager->getPreviousPage()).' ';
    // Pages one by one
    $links = array();
    foreach ($pager->getLinks() as $page)
      $links[] = link_to_unless($page == $pager->getPage(), $page, $uri.$page);
    $navigation .= join('  ', $links);
    // Next and last page
    if ($pager->getPage() != $pager->getLastPage())
      $navigation .= ' '.link_to(image_tag('/sf/images/sf_admin/next.png', 'align=absmiddle'), $uri.$pager->getNextPage());
      $navigation .= link_to(image_tag('/sf/images/sf_admin/last.png', 'align=absmiddle'), $uri.$pager->getLastPage());
  return $navigation;

In your templates, display the pagination links like that:

<?php echo use_helper('Pagination') ?>
<?php echo pager_navigation($mypager, '@myrule') ?>
by Francois Zaninotto on 2006-05-20, tagged helper  pager  pagination  propel 

Load data batch

Create a batch/load_data.php script with:

define('SF_ROOT_DIR',    realpath(dirname(__FILE__).'/..'));
define('SF_APP',         'frontend');
define('SF_ENVIRONMENT', 'dev');
define('SF_DEBUG',       true);
// initialize database manager
$databaseManager = new sfDatabaseManager();
$data = new sfPropelData();

Call it with:

$ cd batch
$ php load_data.php

It will load the data contained in all the .yml files of the data/fixtures/ directory.

by Francois Zaninotto on 2006-05-20, tagged batch  data  propel 

Use transaction in the model

$con = Propel::getConnection();
  // do something
catch (Exception $e)
  throw $e;
by Fabien Potencier on 2006-05-20, tagged propel  transaction 

Use InnoDB with Propel

To enable InnoDB support in Propel, you can add this line at the end of your config/propel.ini configuration file:

propel.mysql.tableType = InnoDB
by Fabien Potencier on 2006-05-20, tagged mysql  propel