Sign up to create your own snipts, or login.

Public snipts » symfony The latest public symfony snipts.

showing 1-20 of 34 snipts for symfony
  • HowTo define custom filter in formFilter class
    /**
     * Esempio di utilizzo di filtri 
     * su tabelle esterne in una classe di 
     * filtro autogenerata (classi *Filter 
     * utilizzate, ad esempio, nell'admin generator)
     * 
     * Nell'esempio, per la classe Comment viene generato
     * il form di filtro CommentFormFilter. All'interno del
     * form si vuole dare la possibiltà di filtrare anche per i 
     * campi url e title della tabella relazionata Item.
     * Le classi *Filter permettono di definire filtri custom
     * sostanzialmente in due modi:
     * * Definendo dei metodi addNomeCampoColumnQuery() per manipolare la query aggiungendo i filtri necessari a NomeCampo
     * * Definendo la tipologia del filtro custome con il metodo getFields() e poi definendo un metodo addTipoFieldQuery() che manipoli la query per tutti i campi di uno stesso tipo.
     * 
     * A causa della issue 7952 (http://trac.symfony-project.org/ticket/7952) la seconda
     * opzione non è utilizzabile in quanto non viene fatto correttamente il check sull'esistenza
     * del metodo addTipoFieldQuery(). 
     * Questo snippet aggira il problema definendo un metodo per ogni campo custom definito. Per 
     * centralizzare il codice di modifica della query è previsto cmq un solo metodo addItemQuery
     * per manipolare la query.
     * 
     * NOTA: Nella maggior parte dei casi i campi di test nelle classi di filtro
     * hanno widget di tipo sfWidgetFormFilterInput() che prevedono due diversi controlli:
     * * un campo di testo per il valore
     * * una checkbox per la ricerca del valore vuoto
     * Utilizzando questo tipo di widget l'array values contiene due chiavi: 
     * * text contiene il valore di testo
     * * is_empty indica se cercare il valore null su db.
     * Utilizzando questo widget il metodo addxxxQuery dovrà tenere conto di questi valori
     * comportarsi di conseguenze. In questo snippet ai campi extra corrispondono dei semplici
     * widget di testo.
    */
    
    /**
     * Comment filter form.
     *
     * @package    core
     * @subpackage filter
     * @author     Your name here
     * @version    SVN: $Id: sfDoctrineFormFilterTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
     */
    class CommentFormFilter extends BaseCommentFormFilter
    {
      /**
       * Alias per la join della relazione Item
       * @var string
       */
      protected $itemAlias = 'i';
    
      /**
       * @see SocialEntityFormFilter
       */
      public function configure()
      {
        parent::configure();
    
        $this->widgetSchema['url'] = new sfWidgetFormInput();
        $this->validatorSchema['url'] = new sfValidatorString(array('required' => false));
    
        $this->widgetSchema['title'] = new sfWidgetFormInput();
        $this->validatorSchema['title'] = new sfValidatorString(array('required' => false));
      }
    
      /**
       * (non-PHPdoc)
       *
       * @internal A causa del bug 7952 la definizione dei fields non è indispensabile
       * e viene commentata
       *
       * @see lib/filter/doctrine/sfDoctrineGuardPlugin/base/BasesfGuardUserFormFilter#getFields()
       */
      //  public function getFields()
      //  {
      //    $fields = parent::getFields();
      //    return array_merge($fields, array(
      //      'url'  =>   'Item',
      //      'title'  => 'Item',
      //    ));
      //  }
    
      /**
       * Aggiunge parametri custom alla query per filtrare
       * in base al valore di url
       *
       * @param Doctrine_Query $query
       * @param string $field
       * @param string $values
       */
      public function addUrlColumnQuery(Doctrine_Query $query, $field, $values)
      {
        $this->addItemQuery($query, $field, $values);
      }
    
      /**
       * Aggiunge parametri custom alla query per filtrare
       * in base al valore di title
       *
       * @param Doctrine_Query $query
       * @param unknown_type $field
       * @param unknown_type $values
       * @return unknown_type
       */
      public function addTitleColumnQuery(Doctrine_Query $query, $field, $values)
      {
        $this->addItemQuery($query, $field, $values);
      }
    
      /**
       * Aggiunge alla query i filtri relativi ai campi della tabella item
       *
       *
       * @internal A causa di un bug (issue 7952) nell'implementazione di
       * sfFormFilterDoctrine::doBuildQuery il metodo non viene chiamato direttamente
       * ma è necessario specificare i metodi addTitleColumnQuery() e addUrlColumnQuery()
       *
       * @param Doctrine_Query $query
       * @param unknown_type $field
       * @param unknown_type $values
       * @return unknown_type
       */
      public function addItemQuery(Doctrine_Query $query, $field, $values)
      {
        $fieldName = Doctrine::getTable('comment')->getFieldName($field);
        $query = $this->joinItem($query);
    
        if (!empty($values))
        {
          $query->addWhere(sprintf('%s.%s = ?', $this->itemAlias, $fieldName), $values);
        }
      }
    
      /**
       * Aggiunge alla  query la join con la relazione Item
       *
       * @param Doctrine_Query $query
       * @return Doctrine_Query
       */
      protected function joinItem(Doctrine_Query $query)
      {
        $alias = $query->getRootAlias();
        if (!$query->contains(sprintf('JOIN %s.Item %s', $alias, $this->itemAlias)))
        {
          $query->leftJoin(sprintf('%s.Item %s', $alias, $this->itemAlias));
        }
        return $query;
      }
    }
    

    copy | embed

    0 comments - tagged in  posted by ftassi on Mar 02, 2010 at 2:07 p.m. EST
  • symfony filter to check db availability
    <?php
    // symfony filter to check db availability 
    class checkAvailibilityDbFilter extends sfFilter
    {
      public function execute($filterChain)
      {
        if ($this->isFirstCall())
        {
          $context = $this->getContext();
    
          $module = sfConfig::get('app_checkdb_module', 'default');
          $action = sfConfig::get('app_checkdb_action', 'error404');
    
          if (($module != $context->getModuleName()) || ($action != $context->getActionName()))
          {
            $configuration = sfProjectConfiguration::getActive();
            $db = new sfDatabaseManager($configuration);
    
            foreach ($db->getNames() as $connection)
            {
              try
              {
                @$db->getDatabase($connection)->getConnection();
              }
              catch(Exception $e)
              {
                 $context->getController()->forward($module, $action);
                 exit;
              }
            }
          }
        }
    
        $filterChain->execute();
      }
    }
    ?>
    // in your app.yml file
    all:
      checkdb:
        module: default
        action: checkAvailibility
    
    
    // in your filters.yml file
    rendering: ~
    security:  ~
    
    # insert your own filters here
    db:
      class:  checkAvailibilityDbFilter
    
    cache:     ~
    common:    ~
    execution: ~
    

    copy | embed

    0 comments - tagged in  posted by gestadieu on Feb 26, 2010 at 9:18 p.m. EST
  • restore DB with PHP script+ajax
    <?php
    //restore.php to restore DB with SQL dump file,please look at backup.php in snipts
    
    include('db_config.php');
    //$files =scandir($backup_dir);
    //$filepath = $backup_dir.$files[2];
    
    $filepath =getNewestFile(getPathOfFiles($backup_dir));
    restore($dbhost, $dbuser, $dbpassword, $dbname, $filepath);
    echo sprintf('[%s] DB restored successed !<br><small>Used %s</small><br>',date('Y-m-d H:i:s'),$filepath);
    
    
    //get filepath of newest file in $backup_dir
    function getNewestFile($path_array){
      //init. datetime with the value of first file
      $max_datetime = filemtime($path_array[0]);
      //init. index with 0
      $newest = 0;
      
      //find the newest file
      foreach($path_array as $i=> $path){
        //if its datetime bigger, means it is newer.
        if(filemtime($path) > $max_datetime){
          $max_datetime = filemtime($path);
          $newest= $i;
        }
      }
      //return the filePath of newest file
      return $path_array[$newest];
    }//end getNewestFile()
    
    //build a array of filepath, in order to find the newest file with filemtime()
    function getPathOfFiles($backup_dir){
      //create a new array to store the pathes
      $path_array = array();
      $files =scandir($backup_dir);//return a array of filenames
      foreach($files as $file){
        if($file != '.' && $file !='..'){//we don't need the dir '.' and '..'
          $path_array[] = $backup_dir.$file;//build the path and put it in array
        }
      }
      //return a array of filepath as result
      return $path_array;
    }//end getPathOfFiles()
     
    function restore($dbhost, $dbuser, $dbpassword, $dbname, $filepath)
    {
      // Connect to MySQL server
      mysql_connect($dbhost, $dbuser, $dbpassword) or die('Error connecting to MySQL server: ' . mysql_error());
      // Select database
      mysql_select_db($dbname) or die('Error selecting MySQL database: ' . mysql_error());
     
      // Temporary variable, used to store current query
      $templine = '';
      // Read in entire file
      $lines = file($filepath);
      // Loop through each line
      foreach ($lines as $line)
      {
    	  // Skip it if it's a comment
    	  if (substr($line, 0, 2) == '--' || $line == '')
    		  continue;
      	// Add this line to the current segment
    	  $templine .= $line;
    	  // If it has a semicolon at the end, it's the end of the query
    	  if (substr(trim($line), -1, 1) == ';')
    	  {
    		  // Perform the query
    		  mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
    		  // Reset temp variable to empty
    		  $templine = '';
    	  }
      }//end foreach 
    }//end restore()
    
    ?>
    

    copy | embed

    0 comments - tagged in  posted by toledot on Feb 23, 2010 at 7:35 a.m. EST
  • hide a widget with default value in symfony 1.2
    <?php
    // to hide a widget with default value
    $this->setWidget('conference_id', new sfWidgetFormInputHidden(array(),array('value' => ConferencePeer::getActiveConferenceId())));
    

    copy | embed

    0 comments - tagged in  posted by toledot on Feb 23, 2010 at 7:19 a.m. EST
  • submit a form when a hyperlink or image is clicked
    // Sample code 1: pure PHP and javascript
    <form name="myform" action="handle-data.php">
    Search: <input type='text' name='query' />
    <a href="javascript: submitform()">Search</a>
    </form>
    <script type="text/javascript">
    function submitform()
    {
      document.myform.submit();
    }
    </script> 
    
    //Sample code 2: symfony and jQueryHelper
    // form to submit
    <form action="<?php echo url_for('semester/batchDelete') ?>" name="batchform" method="post">
    </form>
    //define a method to submit form in javascript
    <?php echo javascript_tag("
      function submitBatchForm(){
        document.batchform.submit();
      }
    ") ?>
    <?php echo jq_link_to_function('delete selection', 'submitBatchForm()') ?>
    

    copy | embed

    0 comments - tagged in  posted by toledot on Feb 19, 2010 at 4:13 p.m. EST
  • Symfony 1.4 file upload
    /**
     * FooModelForm
     *
     * This class has been auto-generated by the Doctrine ORM Framework
     *
     */
    class FooModelForm extends BaseFooModelForm
    {
      
     /**
      * configure
      *
      * Imposta il widget e il validatore per il campo image (e image_delete creato
      * dal sfWidgetFormInputFileEditable
      *
      */
      public function configure()
      {
        
        $this->widgetSchema['image'] = new sfWidgetFormInputFileEditable(
          array(
            'file_src' => SatelliteSitesConfig::getCurrentConfigKey('assets_path') .'/'. $this->getObject()->getImage(),
            'edit_mode' =>    true,
            'is_image'  =>    true,
            'with_delete' =>  true,
          )
        );
        
        $this->validatorSchema['image'] = new sfValidatorFile(
          array(
            'path' => sfConfig::get('sf_upload_dir'), 
            'max_size' => 100000, 
            'mime_categories' => 'web_images'
          )
        );
        $this->validatorSchema['image_delete'] = new sfValidatorBoolean(array('required' => false));
      }
      
     /**
      * updateObject
      *
      * In questo caso il metodo uodateObject si occupa di eliminare il file precedentemente
      * associato all'oggetto (se esiste). In questo modo un nuovo upload elimina anche il
      * precedente.
      * Il salvataggio del file uploadato viene effettuato nel metodo doSave() del form 
      * per tutti i field a cui è associato un sfValidatorFile con parametro path impostato.
      * Per configurare il nome del file è sufficiente definire un metodo FooModel::generate%field_name%Filename() (in questo caso FooModel::generateImageFilename())
      * L'eliminazione del file nel caso in cui venga flaggato il campo _delete viene gestito
      * automaticamente dal form.
      *
      */
      public function updateObject($values = null)
      {
        $actualImage = $this->getObject()->getImage();
        parent::updateObject($values);
        
        if (file_exists(sfConfig::get('sf_upload_dir').DIRECTORY_SEPARATOR.$actualImage))
        {
          unlink(sfConfig::get('sf_upload_dir').DIRECTORY_SEPARATOR.$actualImage);
        }
        
      }
    }
    
    /**
     * FooModel
     *
     * Classe di model relativa al form con l'immagine da uploadare
     *
     */
    class FooModelNews extends BaseFooModel
    { 
      /**
       * Genera il nome file per le immagini delle news.
       * 
       * Il nome delle immagini vengono generate utilizzando l'md5 del nome
       * originale accodato al timestamp del momento in cui viene uploadato 
       * il file
       * 
       * @param sfValidatedFile $file
       * @return string
       */
      public function generateImageFilename(sfValidatedFile $file)
      {
        return md5($file->getOriginalName() . time()) . $file->getOriginalExtension();
      }
    }
    

    copy | embed

    0 comments - tagged in  posted by ftassi on Feb 19, 2010 at 7:08 a.m. EST
  • hide or close div with jq_link_to_remote, jquery, jq_visual_effect
    <div id="feedback" class="hide">feedback: </div>
    <?php echo jq_link_to_function('show secret div','$("#feedback").removeClass("hide")') ?>
    <?php echo jq_link_to_function('hide secret div','$("#feedback").addClass("hide")') ?>
    <?php echo jq_link_to_function('show secret div with effect',jq_visual_effect('fadeIn', '#feedback'),) ?>
    <?php echo jq_link_to_function('show secret div with effect',jq_visual_effect('fadeOut', '#feedback'),) ?>
    <?php echo jq_link_to_function('show secret div with effect','$("#feedback").fadeIn(1000)') ?>
    
    <?php echo jq_link_to_function('show secret div with effect','$("#feedback").fadeOut(1000)') ?>
    
    
    <?php echo jq_link_to_function('show secret div with effect',jq_visual_effect('slideDown', '#feedback'),) ?>
    
    <?php echo jq_link_to_function('hide secret div with effect',jq_visual_effect('slideUp', '#feedback'),) ?>
    

    copy | embed

    0 comments - tagged in  posted by toledot on Feb 13, 2010 at 2:07 p.m. EST
  • view symfony log file
    $ tail -f log/frontend_dev.log
    

    copy | embed

    0 comments - tagged in  posted by toledot on Jan 28, 2010 at 5:30 p.m. EST
  • PHP reads from text file and write into YML file
    <?
    $arr=file("province.txt");// the txt file to be read
    // read the data from province.txt and write into 02_district.yml
    $myFile = "02_district.yml"; 
    //open a new file with name $myFile, if permission is dennied, throws message
    $fh = fopen($myFile, 'w') or die("can't open file");
    // write the head in YML file without backspace
    $head= "District:\n";
    fwrite($fh, $head);
    $i = 0;
    $k = 0;
    $tmp = "province";
    foreach($arr as $str)
    {
      $k++;
      // split $str, if digits were found
      list($province,$district)=preg_split("/[\d]+/", $str);;
      /*echo "<ul>";
      echo "<li>".$province;
      echo "<li>".$district;
      echo "</ul>";
      echo "<hr>";*/
    
      $district_id = "  District_".$k.":\n";// \n change line
      $district_name = "    name:  ".$district."";
      if($tmp != $province){//if province is changed, increase the id of province
    	  $i++;  
    	  $tmp = $province;
      }
      $province_id = "    province_id:  Province_".$i."\n";
      fwrite($fh, $district_id);//write the value in file
      fwrite($fh, $district_name);
      fwrite($fh, $province_id);
    }
    fclose($fh);
    
    ?> 
    
    // this is text file to be read by PHP script
    Nuristan	3001	Nuristan
    Nuristan	3002	Kamdesh
    Nuristan	3003	Waygal
    Nuristan	3004	Mandol
    Nuristan	3005	Bargi Matal
    Nuristan	3006	Wama
    Nuristan	3007	Du Ab
    Nuristan	3008	Nurgaram
    Sari Pul	3101	Sari Pul
    Sari Pul	3102	Sangcharak
    Sari Pul	3103	Kohistanat
    Sari Pul	3104	Balkhab
    Sari Pul	3105	Sozma Qala
    Sari Pul	3106	Sayyad
    Sari Pul	3107	Gosfandi
    

    copy | embed

    0 comments - tagged in  posted by toledot on Jan 28, 2010 at 2:05 p.m. EST
  • symfony form snipts 01
    <?
    //set default value
    $user_church = sfContext::getInstance()->getUser()->getGuardUser()->getChurchId();
    $this->setDefault('church_id', $user_church);
    
    // change the labels for a form
    $this->widgetSchema->setLabels(array(
          'category_id'=>'Category',
          'is_public'=>'public ?',
        ));
    
    // move field within widget
    $this->widgetSchema->moveField('password_again', 'after', 'password');
    
    //hidden input with default value
    $this->setWidget('conference_id', new sfWidgetFormInputHidden(array(),array('value' => ConferencePeer::getActiveConferenceId())));
    

    copy | embed

    0 comments - tagged in  posted by toledot on Jan 15, 2010 at 11:52 a.m. EST
  • Propel VS Doctrine in symfony
    <?php 
    
    //Retrieving an article by its primary key
    // Propel
    $article = ArticlePeer::retrieveByPk(123);
    // Doctrine
    $article = Doctrine::getTable('Article')->find(123);
    // sfPropelFinder
    $article = sfPropelFinder::from('Article')->findPk(123);
    
    //Retrieving the comments related to an article
    // Propel
    $comments = $article->getComments();
    // Doctrine
    $comments = $article->Comments;
    // sfPropelFinder
    $comments = $article->getComments(); // no change – use Propel
    Retrieving an article from its title
    // Propel
    $c = new Criteria();
    $c->add(ArticlePeer::TITLE, 'FooBar');
    $article = ArticlePeer::doSelectOne($c);
    
    // Doctrine
    $article = Doctrine_Query::create()->
    from('Article a')->
    where('a.title = ?', array('FooBar'))->
    fetchOne();
    // Doctrine (faster)
    $article = Doctrine::getTable('Article')->
    findOneByTitle('FooBar');
    
    // sfPropelFinder
    $article = sfPropelFinder::from('Article')->
    where('Title', 'FooBar')->
    findOne();
    // sfPropelFinder (faster)
    $article = sfPropelFinder::from('Article')->
    findOneByTitle('FooBar');
    Retrieving the latest 5 articles
    // Propel
    $c = new Criteria();
    $c->addDescendingOrderByColumn(ArticlePeer::PUBLISHED_AT);
    $c->setLimit(5);
    $articles = ArticlePeer::doSelect($c);
    
    // Doctrine
    $articles = Doctrine_Query::create()->
    from('Article a')->
    orderby('a.published_at DESC')->
    limit(5)->
    execute();
    
    // sfPropelFinder
    $articles = sfPropelFinder::from('Article')->
    orderBy('PublishedAt', 'desc')->
    find(5);
    Retrieving the last 5 comments related to an article
    // Propel
    $c = new Criteria();
    $c->addDescendingOrderByColumn(CommentPeer::PUBLISHED_AT);
    $c->setLimit(5);
    $comments = $article->getComments($c);
    
    // Doctrine
    $comments = Doctrine_Query::create()->
    from('Comment c')->
    where('c.article_id = ?', array($article->getId()))->
    orderby('c.published_at DESC')->
    limit(5)->
    execute();
    
    // sfPropelFinder
    $comments = sfPropelFinder::from('Comment')->
    relatedTo($article)->
    orderBy('PublishedAt', 'desc')->
    find(5);
    Retrieving the last comment related to an article
    // Propel
    $c = new Criteria();
    $c->addDescendingOrderByColumn(CommentPeer::PUBLISHED_AT);
    $c->add(CommentPeer::ARTICLE_ID, $article->getId());
    $comment = CommentPeer::doSelectOne($c);
    
    // Doctrine
    $comments = Doctrine_Query::create()->
    from('Comment c')->
    where('c.article_id = ?', array($article->getId()))->
    orderby('c.published_at DESC')->
    fetchOne();
    
    // sfPropelFinder
    $comments = sfPropelFinder::from('Comment')->
    relatedTo($article)->
    findLast();
    Retrieving articles based on a word appearing in the title or the summary
    // Propel
    $c = new Criteria();
    $cton1 = $c->getNewCriterion(ArticlePeer::TITLE, '%FooBar%', Criteria::LIKE);
    $cton2 = $c->getNewCriterion(ArticlePeer::SUMMARY, '%FooBar%', Criteria::LIKE);
    $cton1->addOr($cton2);
    $c->add($cton1);
    $articles = ArticlePeer::doSelect($c);
    
    // Doctrine
    $article = Doctrine_Query::create()->
    from('Article a')->
    where('a.title like ? OR a.summary like ?', array('%FooBar%', '%FooBar%'))->
    execute();
    
    // sfPropelFinder
    $article = sfPropelFinder::from('Article')->
    where('Title', 'like', '%FooBar%')->
    _or('Summary', 'like', '%FooBar%')->
    find();
    Retrieving articles based on a complex AND/OR clause
    // Articles having name or summary like %FooBar% and published between $begin and $end
    
    // Propel
    $c = new Criteria();
    $cton1 = $c->getNewCriterion(ArticlePeer::TITLE, '%FooBar%', Criteria::LIKE);
    $cton1 = $c->getNewCriterion(ArticlePeer::SUMMARY, '%FooBar%', Criteria::LIKE);
    $cton1->addOr($cton2);
    $c->add($cton1);
    $c->add(ArticlePeer::PUBLISHED_AT, $begin, Criteria::GREATER_THAN);
    $c->addAnd(ArticlePeer::PUBLISHED_AT, $end, Criteria::LESS_THAN);
    $article = ArticlePeer::doSelect($c);
    
    // Doctrine
    $article = Doctrine_Query::create()->
    from('Article a')->
    where('(a.title like ? OR a.summary like ?) and (article.published_at> ? and article.published_at> ?)', array('%FooBar%', '%FooBar%', $begin, $end))->
    execute();
    
    // sfPropelFinder
    $article = sfPropelFinder::from('Article')->
    where('Title', 'like', '%FooBar%', 'cond1?)->
    where('Summary', 'like', '%FooBar%', 'cond2?)->
    combine(array('cond1?, 'cond2?), 'or', 'cond3?)->
    where('PublishedAt', '>', $begin, 'cond4?)->
    where('PublishedAt', '<', $end, 'cond5?)->
    combine(array('cond4?, 'cond5?), 'and', 'cond6?)->
    combine(array('cond3?, 'cond6?), 'and')->
    find();
    Retrieving articles authored by someone
    // Propel
    $c = new Criteria();
    $c->addJoin(ArticlePeer::AUTHOR_ID, AuthorPeer::ID);
    $c->add(AuthorPeer::NAME, 'John Doe');
    $articles = ArticlePeer::doSelect($c);
    
    // Doctrine
    $article = Doctrine_Query::create()->
    from('Article a')->
    leftJoin('a.Author b')->
    where('b.name = ?', array('John Doe'))->
    execute();
    
    // sfPropelFinder
    $article = sfPropelFinder::from('Article')->
    where('Author.Name', 'John Doe')-> // Guesses the join from the schema
    find();
    Retrieving articles authored by people of a certain group
    // Propel
    $c = new Criteria();
    $c->addJoin(ArticlePeer::AUTHOR_ID, AuthorPeer::ID);
    $c->addJoin(AuthorPeer::GROUP_ID, GroupPeer::ID);
    $c->add(GroupPeer::NAME, 'The Foos');
    $articles = ArticlePeer::doSelect($c);
    
    // Doctrine
    $article = Doctrine_Query::create()->
    from('Article a')->
    leftJoin('a.Author b')->
    leftJoin('b.Group c')->
    where('c.name = ?', array('The Foos'))->
    execute();
    
    // sfPropelFinder
    $article = sfPropelFinder::from('Article')->
    join('Author')->
    where('Group.Name', 'The Foos')-> // Guesses the Group join from the schema
    find();
    Retrieving all articles and hydrating their category object in the same query
    // Propel
    $c = new Criteria();
    $articles = ArticlePeer::doSelectJoinCategory($c);
    
    // Doctrine
    $article = Doctrine_Query::create()->
    from('Article a')->
    leftJoin('a.Category c')->
    execute();
    
    // sfPropelFinder
    $article = sfPropelFinder::from('Article')->
    with('Category')->
    find();
    Retrieving an article and its category by the article primary key
    // Propel
    $c = new Criteria();
    $c->add(ArticlePeer::ID, 123);
    $c->setLimit(1);
    $articles = ArticlePeer::doSelectJoinCategory($c);
    $article = isset($articles[0]) ? $articles[0] : null;
    
    // Doctrine
    $article = Doctrine_Query::create()->
    from('Article a')->
    leftJoin('a.Category c')->
    where('a.id = ?', array(123))->
    fetchOne();
    
    // sfPropelFinder
    $article = sfPropelFinder::from('Article')->
    with('Category')->
    findPk(123);
    Retrieving articles and hydrating their author object and the author group
    // Propel
    // Impossible do to it simply – need for a custom hydration method (approx 40 LOC)
    
    // Doctrine
    $article = Doctrine_Query::create()->
    from('Article a')->
    leftJoin('a.Author b')->
    leftJoin('b.Group c')->
    where('a.id = ?', array(123))->
    fetchOne();
    
    // sfPropelFinder
    $article = sfPropelFinder::from('Article')->
    with('Category', 'Group')->
    findPk(123);
    

    copy | embed

    0 comments - tagged in  posted by toledot on Jan 15, 2010 at 7:58 a.m. EST
  • clean local copy from SVN symfony project
    1 create batch_local.txt file in project folder with this content
    for DIR in `find -name sql -type d`; do svn propset svn:ignore '*' $DIR/; done;
    for DIR in `find -name log -type d`; do svn propset svn:ignore '*' $DIR/; done;
    for DIR in `find -name cache -type d`; do svn propset svn:ignore '*' $DIR/; done;
    for DIR in `find -name base -type d`; do svn propset svn:ignore '*' $DIR/; done;
    for DIR in `find -name om -type d`; do svn propset svn:ignore '*' $DIR/; done;
    for DIR in `find -name map -type d`; do svn propset svn:ignore '*' $DIR/; done;
    svn commit -m 'change svn properties'
    svn status
    
    2 $chmod +x batch_local.txt
    3 $./batch_local.txt
    

    copy | embed

    0 comments - tagged in  posted by toledot on Jan 15, 2010 at 6:21 a.m. EST
  • clean copy of symfony project for trac by using batch command
    1 create batch_trac.txt in project folder with this content
    mv config/databases.yml config/databases.yml.sample;
    mv config/ProjectConfiguration.class.php config/ProjectConfiguration.class.php.sample;
    rm -rf cache/* log/*;
    find -name *schema.sql -exec rm -rf {} \;
    for DIR in `find -name base -type d`; do rm -rf $DIR/*;done;
    for DIR in `find -name map -type d`; do rm -rf $DIR/*;done;
    for DIR in `find -name om -type d`; do rm -rf $DIR/*;done;
    echo Clean project sucessfully! please do not forget delete all unnecessary file in project folder, For Example: *.txt for batching
    
    2 $chmod +x batch_trac.txt
    3 $./batch_trac.txt
    4 you can import these code in trac system
    

    copy | embed

    0 comments - tagged in  posted by toledot on Jan 15, 2010 at 6:18 a.m. EST
  • Generator Backend
    $ mkdir classifieds
    $ cd classifieds
    $ symfony generate:project classifieds
    
    $symfony configure:database "mysql:host=localhost;dbname=classifieds" root mYsEcret
    $ mysqladmin -uroot -pmYsEcret create classifieds
    $ symfony propel:build-all-load
    
    generate App Backend
    $symfony generate:app --escaping-strategy=on --csrf-secret=UniqueSecret1 backend
    
    
    generate a module named"conference" for App backend
    $symfony propel:generate-admin backend DemoAd
    

    copy | embed

    0 comments - tagged in  posted by toledot on Jan 14, 2010 at 5:40 a.m. EST
  • Nahomail & swiftmailer
    #nahomail
    $ symfony plugin-upgrade nahomailplugin
    
    # From http://pear.swiftmailer.org/
    $ sudo pear channel-discover pear.swiftmailer.org
    $ sudo pear remote-list -c swift
    $ sudo pear install swift/swift-4.0.5
    

    copy | embed

    0 comments - tagged in  posted by tayhimself on Jan 11, 2010 at 2:45 p.m. EST
  • symfony project generation
    $ symfony generate:project iom
    $ php syfony generate:app --escaping-strategy=on --csrf-secret=iomsurvey survey
    

    copy | embed

    0 comments - tagged in  posted by tayhimself on Dec 04, 2009 at 1:27 p.m. EST
  • symfony pear installation and upgrade
    $ pear channel-discover pear.symfony-project.com
    # to only upgrade the pear channels and not the symfony channel
    $ sudo pear upgrade pear
    # to upgrade the symfony channel to the latest 1.2 version
    # a pear upgrade-all would get symfony 1.4
    $ sudo pear upgrade symfony/symfony-1.2.10
    

    copy | embed

    0 comments - tagged in  posted by tayhimself on Dec 01, 2009 at 6:32 p.m. EST
  • Create symfony guard user
    $ symfony guard:create-user --application=frontend jon SoMePasSwOrD
    

    copy | embed

    0 comments - tagged in  posted by tayhimself on Nov 10, 2009 at 10:52 a.m. EST
  • Pagination in symfony with doctrine
    //action
    $this->pager = new sfDoctrinePager( 'Table', 3 ); // Table, items per page
    $this->pager->setQuery( $query ); // items query   
    $this->pager->setPage( $request->getParameter('page', 1) ); // actual page
    $this->pager->init(); 
    
    //view
    <?php $table_list = $pager->getResults(); ?>
    
    <!-- pages -->
    <?php if ($pager->haveToPaginate()): ?>
      <div class="pagination">
    
        <a href="<?php echo url_for( sprintf($page_link, $pager->getFirstPage() ) ) ?>">Pierwsza</a>
        <a href="<?php echo url_for( sprintf($page_link, $pager->getPreviousPage() )); ?>">Poprzednia</a>
     
        <?php foreach ($pager->getLinks() as $page): ?>
          <?php if ($page == $pager->getPage()): ?>
            <?php echo $page ?>
          <?php else: ?>
            <a href="<?php echo url_for( sprintf($page_link, $page) ) ?>"><?php echo $page ?></a>
          <?php endif; ?>
        <?php endforeach; ?>
    
        <a href="<?php echo url_for( sprintf($page_link, $pager->getNextPage() ) ) ?>">Nast?pna</a>
        <a href="<?php echo url_for( sprintf($page_link, $pager->getLastPage() ) ) ?>">Ostatnia</a>
      </div>
      <?php else:?>
        <p>&nbsp;</p>
      <?php endif; ?>
    

    copy | embed

    0 comments - tagged in  posted by boom3 on Oct 21, 2009 at 4:04 a.m. EDT
  • Remove auto-generated files from svn tree
    $ for DIR in `find lib -name base -type d`; do svn propset svn:ignore base $DIR/..;svn rm $DIR; done;
    

    copy | embed

    0 comments - tagged in  posted by tayhimself on Sep 05, 2009 at 11:57 a.m. EDT
Sign up to create your own snipts, or login.