Code snippets for symfony 1.x

Navigation

Snippets by user Loïc Vernet

[Symfony2] Extract the current namespace, bundle, controller and action name

Sometimes, you may have to know, at the controller level what are these informations, it can be easily achieved with the following regexp: (inside a controller action function)

$matches    = array();
$controller = $this->getRequest()->attributes->get('_controller');
preg_match('/(.*)\\\Bundle\\\(.*)\\\Controller\\\(.*)Controller::(.*)Action/', $controller, $matches);
 
$request = $this->getRequest();
$request->attributes->set('namespace',  $matches[1]);
$request->attributes->set('bundle',     $matches[2]);
$request->attributes->set('controller', $matches[3]);
$request->attributes->set('action',     $matches[4]);
 

These informations are now available in the action attributes:

For example:

echo 'namespace: '. $request->attributes->get('namespace'). PHP_EOL;
echo 'bundle: '. $request->attributes->get('bundle'). PHP_EOL;
echo 'controller: '. $request->attributes->get('controller'). PHP_EOL;
echo 'action: '. $request->attributes->get('action'). PHP_EOL;
 

Will output:

namespace: COil
bundle: ToolsBundle
controller: Home
action: index
 

See you. COil

PS: This can be useful in a preExecute() like function.

PS2: The namespace here is the parent directory where is stored the bundle.

by Loïc Vernet on 2012-03-17, tagged action  controller  preexecute  symfony2 

Noscript "off" in dev with "prod" controller and "on" in prod with the same settings.yml file

[Edit 06/02/09] Enabling the apache mod_rewrite is a little faster than using this snippet. ;)

Well if you are using Windows + Wamp for your dev, the "noscript" setting (settings.yml) does not work well when you are using the prod controller to test your application with you dev computer. (if mod_rewrite is not installed)

So i wanted to deactivate this settings in dev environment with the prod controller and having it on in prod with the prod controller without having 2 different settings.yml files.

So here here a small tip for this:

prod:
  .settings:
    no_script_name:         <?php echo ((isset($_SERVER['HTTP_HOST']) && strstr($_SERVER['HTTP_HOST'], 'dev') ? 'off' : 'on')) . "\n"; ?>
    logging_enabled:        on
 

This code assumes that your dev url contains "dev" like http://dev.blogsnippets.com.

by Loïc Vernet on 2009-01-19, tagged dev  noscript  prod  settings 
(2 comments)

Debug an object or variable with additional informations

This function allows you to dump the value of a variable or an object.If available the function tells the file, line, function, class where it was called.

1st parameter

The object/variable to debug

2nd parameter

The name that you want to give to the debuged object (var by default)

3nd parameter

Allows you can stop the process or not. If the process is not stopped the debug message is available in the sf debug bar.

/**
   * Function that dumps an array or an object in the SF debug infos or
   * on s"\n"een/console
   *
   * @param $var mixed variable to dump
   * @param $die boolean Tells the function to stop the process or not
   *
   * @author Vernet Loic
   * @since  24 sept. 2006
   */
  public static function dump($var, $name = 'var', $die = false)
  {
      ob_start();
      print('<br/><pre>'. $name . ' :<br/>');
      print_r($var);
      print('</pre></br>');
      $buffer = ob_get_contents();
      ob_end_clean();
 
      $backtrace = debug_backtrace();
      $dieMsg  = '<pre><b>var dump by goTools:dump()</b>'. "\n";
      $dieMsg .= isset($backtrace[0]['file']) ?     '» file     : <b>'.
      $backtrace[0]['file'] .'</b>'. "\n" : '';
      $dieMsg .= isset($backtrace[0]['line']) ?     '» line     : <b>'.
      $backtrace[0]['line'] .'</b>'. "\n" : '';
      $dieMsg .= isset($backtrace[1]['class']) ?    '» class    : <b>'.
      $backtrace[1]['class'] .'</b>'. "\n" : '';
      $dieMsg .= isset($backtrace[1]['function']) ? '» function : <b>'.
      $backtrace[1]['function'] .'</b>'. "\n" : '';
      $dieMsg .= '</pre>';
 
      print($buffer);
 
      if ($die == true) {
          die($dieMsg);
      } else {
          print($dieMsg);
          sfWebDebug::getInstance()->logShortMessage($buffer);
      }
  }
 
by Loïc Vernet on 2007-12-20, tagged debug 
(4 comments)

Multi sort in admin generator

Here we go !

The sort in admin generator is for a single field only, but in some complex list, it can be usefull to sort by multiple criterias. This is the main goal of this snippet. Those functions therefore override the ones of your auto-generated class. (1) And to display what are the ongoing sort criterias, you have to modify your '_list_th_tabular.php' file.

1 - In your 'action.class.php'

//
    /**
     * Add a sort criteria
     */
    protected function processSort ()
    {
        $sort = $this->getRequestParameter('sort');
        $type = $this->getRequestParameter('type');            
 
        // Register sort                 
        if ($sort) {
            $this->getUser()->setAttribute($sort, $type, 'sf_admin/produits/sort');
        }
    }    
 
    /**
     * Add the sort criterias to the query
     */
    protected function addSortCriteria(&$c)
    {
        $multisort = $this->getUser()->getAttributeHolder()->getAll('sf_admin/produits/sort');
 
        if ($multisort) {
            foreach($multisort as $sort_column => $sort_type) {
                $sort_column = Propel::getDB($c->getDbName())->quoteIdentifier($sort_column);
                if ($sort_type == 'asc') {
                    $c->addAscendingOrderByColumn($sort_column);
                }
                elseif ($sort_type == 'desc') {
                    $c->addDescendingOrderByColumn($sort_column);
                }
            }
        } else {
            // Default sort 
            $sort_column = Propel::getDB($c->getDbName())->quoteIdentifier('libelle');
            $c->addAscendingOrderByColumn($sort_column);            
        }
    }
 
    /**
     * Specific function for multi-sort
     */
    protected function processFilters ()
    {
        if ($this->getRequest()->hasParameter('filter'))
        {
            $filters = $this->getRequestParameter('filters');            
 
            // Multi-sort initialisation
            if (!is_array($filters)) {
                $this->getUser()->getAttributeHolder()->removeNamespace('sf_admin/produits/sort');
            }
 
            $this->getUser()->getAttributeHolder()->removeNamespace('sf_admin/produits/filters');
            $this->getUser()->getAttributeHolder()->add($filters, 'sf_admin/produits/filters');
        }
    }

2 - In '_list_th_tabular.php'

(for each sortable field)

<?php 
 
$multisort = $sf_user->getAttributeHolder()->getAll('sf_admin/produits/sort');
 
?>
 
    <th id="sf_admin_list_th_libelle">
        <?php 
        if (isset($multisort['libelle'])) {
            echo link_to('Libellé', 'Produits/list?sort=libelle&type='. ($multisort['libelle'] == 'asc' ? 'desc' : 'asc'));
            echo ' ('. $multisort['libelle'] . ')';
        } else {
            echo link_to('Libellé', 'Produits/list?sort=libelle&type=asc'); 
        }
        ?>
    </th>

'Produits' is the module name, 'libelle' is the field to sort.


Notes:

The 'reset button' of filters also initialize the multi-sort. The sort is made from the first field clicked to the last. That means, if you want a different primary sort you will have to use the reset filter button before.

PS: Obviously, this modification can be easly integrated in your backoffice theme, note that the default sort criteria set in the 'generator.yml' is used in the addSortCriteria function (from line // default sort)

COil :)

by Loïc Vernet on 2006-10-17, tagged admin  generator  multi  sort 
(6 comments)