Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "action view"

Making variables available to all Actions via Filters

I had an urgent need to assign a variable across all actions, and copy and pasting the same snippet of code just didn't appeal to me.

Failing to find the answer in the forums or in the Snippets, I decided to roll up my sleeves and dig into creating it as a filter.

After much experimentation and documentation re-reading, I think I finally found a solution.

First you have to set up your own filter. Since it's fairly well laid out in the Handbook, I won't go over it here. (http://www.symfony-project.org/book/1_0/06-Inside-the-Controller-Layer#Filters)

In your filter code, put the following:

class myFilter extends sfFilter
{
  public function execute($filterChain)
  {
    // Remove this if condition if you want the variable available to AJAX actions
    if (!$this->getContext()->getRequest()->isXmlHttpRequest()) {      
      for ($i=0; $i < $this->getContext()->getActionStack()->getSize(); $i++) { 
        $this->getContext()->getActionStack()->getEntry($i)->getActionInstance()->foo = 'foo';
      }
    }
 
    // Execute next filter
    $filterChain->execute();
  }
}
 

Replace foo with the variable name you want and assign it the data you need. You should now be able to access it in every action that you call.

For example in your action:

class indexAction extends sfAction
{
  public function execute()
  {
    strtoupper($this->foo);
  }
}
 

or in your view:

  <?php echo $foo ?>
 
by Joe Guetler on 2008-03-12, tagged action  actions  filter  view 
(3 comments)