IMPORTANT!

Snipt is going open source. We've toyed with this idea for quite a while, and have finally decided it's the right way to move forward.

A few things:
  • The entire Snipt source code will be released on GitHub under the 3-clause BSD License on Friday, September 10th.
  • While we'd like to think we're perfect, we realize we're only human. By open sourcing the software that runs this website, certain bugs or security flaws may be discovered that could compromise the privacy of your snipts.
  • Only the Lion Burger team will be able to push commits to the Snipt.net site. Contributors should send a pull request to add new features or submit patches.
  • By using this site, you agree not to be too angry or take any legal action against Lion Burger should this whole thing go up in flames some day.
  • Follow us on Twitter for updates.
I agree, close this message
Sign up to create your own snipts, or login.

Latest 100 public snipts » symfony The latest public symfony snipts.

showing 1-20 of 57 snipts for symfony
  • Starts to translate FormChoices in filters for boolean columns
    /**
     * Project filter form base class.
     *
     * @package    filters
     *
     */
    abstract class BaseFormFilterDoctrine extends sfFormFilterDoctrine
    {
        /**
         * Used in generated forms when models use inheritance.
         */
        protected function setupInheritance()
        {
            // Nastaveni prekladoveho slovniku pro form formater
            $this->widgetSchema->getFormFormatter()->setTranslationCatalogue('messages');
        }
    }
    

    copy | embed

    0 comments - tagged in  posted by mailo on Jun 09, 2010 at 1:37 p.m. EDT
  • symfonty textarea attributes
     <?php 
    $this->getWidget('data')->setAttribute('cols', 50);
    $this->getWidget('data')->setAttribute('rows', 20);
    ?>
    

    copy | embed

    0 comments - tagged in  posted by manec on Jun 09, 2010 at 7:55 a.m. EDT
  • Symfony cookies
    #in factories.yml under the section all add 
     storage: 
        class: sfSessionStorage 
        param: 
          session_name: cookieName
    

    copy | embed

    0 comments - tagged in  posted by tayhimself on Jun 01, 2010 at 12:33 p.m. EDT
  • Browser culture detection
    <?php
    /**
     * Setup user culture from request
     * 
     * from http://www.symfony-project.com/snippets/snippet/80
     * Thanks to François Zaninotto
     * Thanks to Garfield-fr on #symfony-fr
     * 
     * Add the following lines in your app.yml to configure your application available languages.
     *   all:
     *     accepted:
     *       languages: [en, fr]
     * 
     * Then add this to your filters.yml
     * 
     *   # Filter that setup user culture
     *   mySwitchLanguageFilter:
     *     class: SwitchLanguageFilter
     * 
     * @package    SwitchLanguageFilter
     * @subpackage filter
     * @author     Pierre-Yves Landuré <py.landure@dorigo.fr>
     */
     
    class SwitchLanguageFilter extends sfFilter
    {
     
      /**
       * Check that the language is a valid application culture.
       * @param string $language The tested language code
       * @param string $default_language The default language code
       * 
       * @return string $language if no accepted languages is set,
       *                else $language if it is in accepted languages
       *                else $default_language
       */
      private function getAvailableCulture($language, $default_language = null)
      {
        $all_languages = sfConfig::get('app_accepted_languages', array());
     
        if(count($all_languages))
        {
          if(in_array($language, $all_languages)) // Test if language is available
          {
            return $language;
          }
          else // Else test if first part of language is available
          {
            $language_parts = explode('_', $language);
            if(count($language_parts))
            {
              if(in_array($language_parts[0], $all_languages))
              {
                return $language_parts[0];
              }
            }
          }
          return $default_language;
        }
     
        return $language;
      }
     
      /**
       * The filter call.
       */
      public function execute ($filterChain)
      {
        $context = $this->getContext();
        $user = $context->getUser();
     
        $default_culture = sfConfig::get('sf_i18n_default_culture');
        $selected_culture = $user->getCulture();
     
        if(!$user->getAttribute('sf_culture_autodetected', false))
        {
          $browser_languages = $context->getRequest()->getLanguages();
     
          foreach($browser_languages as $language)
          {
            $allowed_culture = $this->getAvailableCulture($language);
            if($allowed_culture)
            {
              $selected_culture = $allowed_culture;
              break;
            }
          }
     
          $user->setAttribute('sf_culture_autodetected', true);
        }
     
        $selected_culture = $context->getRequest()->getParameter('sf_culture', $selected_culture);
        $selected_culture = $this->getAvailableCulture($selected_culture, $default_culture);
        if($selected_culture != $user->getCulture())
        {
          // The user wants to see the page in another language
          $user->setCulture($selected_culture);
        }
     
        $filterChain->execute();
      }
    }
    

    copy | embed

    0 comments - tagged in  posted by manec on May 18, 2010 at 5:59 p.m. EDT
  • symfony global errors
    <?php 
    $num_errores_totales = count($form->getErrorSchema()->getErrors());
    $num_errores_globales = count($form->getErrorSchema()->getGlobalErrors());
    if (0 == $num_errores_totales - $num_errores_globales){
            echo $form->renderGlobalErrors();
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by tayhimself on Apr 01, 2010 at 10:11 a.m. EDT
  • symfony ssl redirect filter
    http://grahamc.com/blog/forcing-ssl-with-symfony-1-2
    

    copy | embed

    0 comments - tagged in  posted by manec on Mar 31, 2010 at 10:58 a.m. EDT
  • Symfony, customize query of admin generator list view
    /**
     * Customize query used to generate 
     * the list(index) view of an admin generator module
     * 
     * To customize the query simply override the buildQuery
     * method of the Actions class or buildQuery of the *FormFilterClass.
     * In most cases is usefull to override the *FormFilterClass where are 
     * also defined the custom add%ColumnName%ColumnQuery
     * 
     * @author Francesco Tassi http://flavors.me/ftassi <tassi.francesco@gmail.com>
     */
    protected function buildQuery()
    {
      $query = parent::buildQuery();
    
      //Query customization
      $query->addWhere('item_id = ?', 1);
      
      return $query;
    }
    

    copy | embed

    0 comments - tagged in  posted by ftassi on Mar 26, 2010 at 11:08 a.m. EDT
  • How to implement a choice in a form?
    http://www.symfony-project.org/cookbook/1_2/en/make-a-choice
    
    The following table summarizes the different configuration of sfWidgetFormChoice  and the renderer widget used by symfony:
    
    sfWidgetFormChoice 	expanded is false 	expanded is true
    multiple is false 	sfWidgetFormSelect 	sfWidgetFormSelectRadio
    multiple is true 	sfWidgetFormSelectMany 	sfWidgetFormSelectCheckbox
    

    copy | embed

    0 comments - tagged in  posted by manec on Mar 26, 2010 at 5:59 a.m. EDT
  • slugify
    <?php
    static public function slugify($text)
    	{
    	 	$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
    	 	$text = trim($text, '-');
    	  	$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    	  	$text = strtolower($text);
    	  	$text = preg_replace('~[^-\w]+~', '', $text);
    		if (empty($text)){
    	    	return 'n-a';
    	  	}
    	  	return $text;
    	}
    ?>
    

    copy | embed

    0 comments - tagged in  posted by manec on Mar 25, 2010 at 12:55 p.m. EDT
  • File uploads in Symfony 1.2, my take
    <?php
    // FILE lib/model/Model.php:
    class Model
    {
      /**
       * Returns the abs path to a subdir of uploads specific for this model.
       *
       * If given a $path, it will be concatenated at the end.
       *
       * @param string $path optional relative path of a file inside the dir
       * @return string      complete path to subdir or file
       */
      public function getUploadPath($path = NULL)
      {
        return sfConfig::get('sf_upload_dir').'/event/' . $path;
      }
    
      /**
       * Returns abs path relative to the docroot.
       *
       * @param string $path
       * @return string
       */
      public function getWebPath($path = NULL)
      {
        return str_replace(sfConfig::get('sf_web_dir'), '', $this->getUploadPath($path));
      }
    }
    
    // FILE lib/form/ModelForm.php:
    class ModelForm extends sfPropelForm
    {
      public function configure() {}
    
      /** 
       * Loops through all form values, updates all files values to be absolute paths relative to the docroot.
       * Calls $model->getWebPath(), but the code is otherwise generally re-usable.
       *  
       * (non-PHPdoc)
       * @see symfony/plugins/sfPropelPlugin/lib/form/sfFormPropel#updateObject($values)
       */
      public function updateObject($values = null)
      {
        $object = parent::updateObject($values);
        foreach ($this->values as $field => $value)
        {
          if ($value instanceof sfValidatedFile)
          {
            $column = call_user_func(array(constant(get_class($object).'::PEER'), 'translateFieldName'), $field, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME);
            $getter = 'get'.$column;
            $setter = 'set'.$column;
            $object->$setter($object->getWebPath($object->$getter()));
          }
        }
        return $object;
      }
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by flevour on Mar 25, 2010 at 11:11 a.m. EDT
  • object routing
    //routing.yml
    job_show_user:
      url:     /job/:company_slug/:location_slug/:id/:position_slug
      class:   sfPropelRoute
      options: { model: JobeetJob, type: object }
      param:   { module: job, action: show }
      requirements:
        id: \d+
        sf_method: [get]
    
    <?php
    class jobActions extends sfActions
    {
      public function executeShow(sfWebRequest $request)
      {
        $this->job = $this->getRoute()->getObject();
     
        $this->forward404Unless($this->job);
      }
     
      // ...
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by manec on Mar 25, 2010 at 7:26 a.m. EDT
  • add html suffic to all routes
    //config/factories.yml
    
    all:
      routing:
        class: sfPatternRouting
        param:
          generate_shortest_url:            true
          extra_parameters_as_query_string: true
          suffix:                           .html
    

    copy | embed

    0 comments - tagged in  posted by manec on Mar 25, 2010 at 5:33 a.m. EDT
  • Symfony User Credentials
    http://librosweb.es/jobeet/capitulo13/la_seguridad_de_la_aplicacion.html
    

    copy | embed

    0 comments - tagged in  posted by manec on Mar 24, 2010 at 8:44 a.m. EDT
  • redirect from component
    <? $this->getController()->redirect ('@homepage'); ?>
    

    copy | embed

    0 comments - tagged in  posted by manec on Mar 24, 2010 at 7:19 a.m. EDT
  • Load helper from action in symfony 1.2, 1.3,1.4
    $this->getContext()->getConfiguration()->loadHelpers('Partial');
    

    copy | embed

    0 comments - tagged in  posted by ftassi on Mar 24, 2010 at 5:26 a.m. EDT
  • web debug database
    //databases.yml
    
    change 
    classname: PropelPDO 
    por 
    class:name: DebugPDO
    

    copy | embed

    0 comments - tagged in  posted by manec on Mar 22, 2010 at 7:38 a.m. EDT
  • sfResizethumbnail
    <?php
    /**
     * sfResizedFile represents a resized uploaded file.
     *
     * @package    symfony
     * @subpackage validator
     * @author     Malas
     * @version    0.1
     */
    class sfResizedFile extends sfValidatedFile
    {
    
    	/**
    	 * Saves the uploaded file.
    	 *
    	 * This method can throw exceptions if there is a problem when saving the file.
    	 *
    	 * If you don't pass a file name, it will be generated by the generateFilename method.
    	 * This will only work if you have passed a path when initializing this instance.
    	 *
    	 * @param  string $file      The file path to save the file
    	 * @param  int    $fileMode  The octal mode to use for the new file
    	 * @param  bool   $create    Indicates that we should make the directory before moving the file
    	 * @param  int    $dirMode   The octal mode to use when creating the directory
    	 *
    	 * @return string The filename without the $this->path prefix
    	 *
    	 * @throws Exception
    	 */
    	public function save($file = null, $fileMode = 0666, $create = true, $dirMode = 0777)
    	{
    		if (is_null($file))
    		{
    			$file = $this->generateFilename();
    		}
    
    		if ($file[0] != '/' && $file[0] != '\\' && !(strlen($file) > 3 && ctype_alpha($file[0]) && $file[1] == ':' && ($file[2] == '\\' || $file[2] == '/')))
    		{
    			if (is_null($this->path))
    			{
    				throw new RuntimeException('You must give a "path" when you give a relative file name.');
    			}
    
    			$smallFile = $this->path.DIRECTORY_SEPARATOR.'s_'.$file;
    			$file = $this->path.DIRECTORY_SEPARATOR.$file;
    		}
    
    		// get our directory path from the destination filename
    		$directory = dirname($file);
    		if (!is_readable($directory))
    		{
    			if ($create && !mkdir($directory, $dirMode, true))
    			{
    				// failed to create the directory
    				throw new Exception(sprintf('Failed to create file upload directory "%s".', $directory));
    			}
    
    			// chmod the directory since it doesn't seem to work on recursive paths
    			chmod($directory, $dirMode);
    		}
    		if (!is_dir($directory))
    		{
    			// the directory path exists but it's not a directory
    			throw new Exception(sprintf('File upload path "%s" exists, but is not a directory.', $directory));
    		}
    		if (!is_writable($directory))
    		{
    			// the directory isn't writable
    			throw new Exception(sprintf('File upload path "%s" is not writable.', $directory));
    		}
    
    		// copy the temp file to the destination file
    		$thumbnail = new sfThumbnail(68, 183, true, true, 85);
    		$thumbnail->loadFile($this->getTempName());
    		$thumbnail->save($smallFile, 'image/jpeg');
    
    		$thumbnail = new sfThumbnail(188, 684, true, true, 85, 'sfGDAdapter');
    		$thumbnail->loadFile($this->getTempName());
    		$thumbnail->save($file, 'image/jpeg');
    
    		// chmod our file
    		chmod($smallFile, $fileMode);
    		chmod($file, $fileMode);
    
    		$this->savedName = $file;
    		return is_null($this->path) ? $file : str_replace($this->path.DIRECTORY_SEPARATOR, '', $file);
    	}
    
    }
    
    //objectForm.class.php
    $this->widgetSchema['imagen'] = new sfWidgetFormInputFileEditable(array(
          'label'     => 'Foto del producto',
          'file_src'  => '/uploads/products/s_'.$this->getObject()->getImagen(),
          'is_image'   => true,
          'edit_mode'   => !$this->isNew(),
          'template'   => '<div>%file%<br />%input%<br />%delete% borrar foto</div>'
        ));
    
    
        //validate widgets.
        $this->validatorSchema['imagen'] = new sfValidatorFile(array(
         'required'   => false,
         'mime_types' => 'web_images',
         'path' => sfConfig::get('sf_upload_dir').'/products',
         'validated_file_class' => 'sfResizedFile',
        ));
        $this->validatorSchema['imagen_delete'] = new sfValidatorPass();
    

    copy | embed

    0 comments - tagged in  posted by manec on Mar 21, 2010 at 10:40 a.m. EDT
  • custom filter
    <?php 
    class VinoFormFilter extends BaseVinoFormFilter
    {
      public function configure()
      {
    
        $this->setWidget('nombre', new sfWidgetFormFilterInput());
        $this->setValidator('nombre', new sfValidatorPass());
    
        $this->validatorSchema->addOption('allow_extra_fields', true); 
      }
    
      public function getFields()
      {
        return array_merge(array('nombre' => 'Nombre'), parent::getFields());
      }
    
      protected function addNombreColumnCriteria(Criteria $criteria, $field, $values){
        $criteria->add(ItemPeer::NOMBRE, "%".$values['text']."%", Criteria::LIKE);
      }
    
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by manec on Mar 20, 2010 at 10:05 p.m. EDT
  • Start coding project
    $ mysqladmin -uroot -p create ashq
    $ php symfony configure:database "mysql:host=localhost;dbname=ashq" sqadri myPasswd
    $ php symfony propel:build-all
    
    $ php symfony propel:generate-module survey map MAP
    

    copy | embed

    0 comments - tagged in  posted by tayhimself on Mar 19, 2010 at 5:41 p.m. EDT
  • Freeze project
    # To freeze a symfony 1.2 project
    $ rm web/sf
    $ symfony project:freeze /usr/share/php/symfony
    

    copy | embed

    0 comments - tagged in  posted by tayhimself on Mar 15, 2010 at 8:27 p.m. EDT
Sign up to create your own snipts, or login.