symfonynerds.com

Nerds who love the symfony-project

Archive for the ‘plugins’ Category

Symfony and pChart

I’ve been making some changes to an app that was using the Google Charts API to draw a couple of line and pie charts in a ‘reporting’ section. Sherif suggested while I was at it, I may as well look for some sexier charts, and a few Googles later came up with pChart. A quick look at their site will tell you it definitely fits the ’sexy’ criteria, and has some very cool features like caching (but who cares about, that main thing is it’s sexy :) ).

There are two ways to get pChart going with Symfony. Probably the easiest is to use xsPchartPlugin which was written specifically for the job and is as simple as running ./symfony plugin:install xsPChartPlugin within your app and creating and chmoding the web/images/tmp/xspchart/ directory it is configured to use.

xsPChartPlugin takes care of a few otherwise manual steps and includes some additional features like a function to clear the image directory. I think it’s a great plugin but I was just a little concerned I then had two things I’d have to keep up to date, the pChart lib and the plugin, or the plugin might fall behind and I’d have to remove it anyway.

Fortunately after installing xsPChartPlugin and seeing how it worked, I could now see easily how pChart would need to be installed for Symfony use, so here’s the steps for using it by itself:

  • Download the latest version (1.27d at time of writing) from here
  • Extract the RAR (warning, it doesn’t extract to it’s own folder by default, so first create a folder eg: pChart-1.27d and put the RAR in there then extract - or do it manually)
  • Move your ‘pChart-1.27d’ folder to ‘lib/vendor/’ under your project
  • In ‘pChart-1.27d/pChart/’ you’ll find the three class files that do all the work. So these get picked up by the Symfony Autoloader, you need to rename them with .php on the end. (eg: pChart.class becomes pChart.class.php)
  • Run a ./symfony cc to clear the cache and autoload the classes
  • Have a look in that folder for some example code to test. Example10.php is good, the bit you need is below. This should be placed in your executeXXX (probably exectureIndex) function in the action.class.php of your module.
     // Dataset definition 
     $DataSet = new pData;
     $DataSet->AddPoint(array(10,2,3,5,3),"Serie1");
     $DataSet->AddPoint(array("January","February","March","April","May"),"Serie2");
     $DataSet->AddAllSeries();
     $DataSet->SetAbsciseLabelSerie("Serie2");
     
     // Initialise the graph
     $Test = new pChart(420,250);
     $Test->drawFilledRoundedRectangle(7,7,413,243,5,240,240,240);
     $Test->drawRoundedRectangle(5,5,415,245,5,230,230,230);
     $Test->createColorGradientPalette(195,204,56,223,110,41,5);
     
     // Draw the pie chart
     $Test->setFontProperties("Fonts/tahoma.ttf",8);
     $Test->AntialiasQuality = 0;
     $Test->drawPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),180,130,110,PIE_PERCENTAGE_LABEL,FALSE,50,20,5);
     $Test->drawPieLegend(330,15,$DataSet->GetData(),$DataSet->GetDataDescription(),250,250,250);
     
     // Write the title
     $Test->setFontProperties("Fonts/MankSans.ttf",10);
     $Test->drawTitle(10,20,"Sales per month",100,100,100);
     
     $Test->Render("example10.png");

    You don’t need to include the

     // Standard inclusions   
     include("pChart/pData.class");
     include("pChart/pChart.class");

    lines obviously as Symfony has taken care of that for us.

  • IMPORTANT: We need to tell pChart more specifically where it’s fonts and output image directories are (this is one of the things xsPChartPlugin takes care of itself if you use it). So in the above example code you need to make the following changes:
      $Test->setFontProperties("Fonts/tahoma.ttf",8);

    becomes (in both spots)

     $Test->setFontProperties(sfConfig::get('sf_lib_dir')."/vendor/pChart-1.27d/Fonts/tahoma.ttf",8);

    Then

     $Test->Render("example10.png");

    becomes

     $Test->Render(sfConfig::get('sf_web_dir') . "/images/pchart/example1.png");

    For the lazy people like me who just want something to cut and paste, the whole thing might look something like:

     public function executeIndex(sfWebRequest $request) {   
     // Dataset definition    
     $DataSet = new pData;
     $DataSet->AddPoint(array(10,2,3,5,3),"Series1");
     $DataSet->AddPoint(array("January","February","March","April","May"),"Series2");
     $DataSet->AddAllSeries();
     $DataSet->SetAbsciseLabelSerie("Series2");
     
     // Initialise the graph
     $Test = new pChart(420,250);
     $Test->drawFilledRoundedRectangle(7,7,413,243,5,240,240,240);
     $Test->drawRoundedRectangle(5,5,415,245,5,230,230,230);
     $Test->createColorGradientPalette(195,204,56,223,110,41,5);
     
     // Draw the pie chart
     $Test->setFontProperties(sfConfig::get('sf_lib_dir')."/vendor/pChart-1.27d/Fonts/tahoma.ttf",8);
     $Test->AntialiasQuality = 0;
     $Test->drawPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),180,130,110,PIE_PERCENTAGE_LABEL,FALSE,50,20,5);
     $Test->drawPieLegend(330,15,$DataSet->GetData(),$DataSet->GetDataDescription(),250,250,250);
     
     // Write the title
     $Test->setFontProperties(sfConfig::get('sf_lib_dir')."/vendor/pChart-1.27d/Fonts/tahoma.ttf",12);
     $Test->drawTitle(10,20,"Sales per month",100,100,100);
     
     $Test->Render(sfConfig::get('sf_web_dir') . "/images/pchart/example1.png");
    }

    All that’s left to do now is show the image by using a normal image tag in your template:

    echo image_tag('pchart/example1.png')

    Now this post doesn’t show you how to use the pChart cache and a lot of other things, but it does get you up and running! It’s personal choice as to whether you want to use the plugin or do it by hand, but either way have fun with these sexy charts! :)

  • 1 Comment
  • Filed under: 1.0, 1.1, 1.2, plugins, tip
  • Symfony & YUI

    This is a bit of a cop out of a post, but tonight I started looking for some info on Symfony & YUI… It’s something I’ve been meaning to look at for a long long time and while I was reading about CSS Frameworks I found out there is one that forms part of YUI, so it spurred me to look some more at it…

    I found this great presentation I thought worth sharing by Dustin Whittle (from Yahoo!) about it here

    For those wanting to starting using it you should check out the main site linked to above and maybe check out the sfYUIPlugin, although it looks a little out of date.

    Have a read. When I start playing around with it myself I’ll post what I learn…

  • 2 Comments
  • Filed under: plugins, tip, tools
  • This is a quick tip that will hopefully save you some time. The sfFormExtraPlugin is an excellent plugin with lots of extra features to help you build your forms. This tip is regarding the sfWidgetFormJQueryDate widget. This Widget lets you create a jQuery date selector. Setting up this widget is simple, but not well documented. Here are the basic steps of getting this started in your project forms:

    1. Install the sfFormExtraPlugin
    ./symfony symfony plugin:install sfFormExtraPlugin

    2. Install relevant jQuery libraries:
    a) Download jQuery AND
    b) Download jQueryUI

    3. Setup jQuery in your project
    Extract the JavaScript libs to your project js folder, then modify your app view.yml to include them:

    javascripts: [jquery-1.3.2.min.js, jquery-ui-1.7.1.custom.min.js]

    Note: The order in which the jQuery libs are included are important and can cause a conflict if they are not in the order above.

    4. Setup the CSS for jQuery UI
    When you download the jQuery UI, extract the smoothness theme into your web css directory. IE:

    /web/css/smoothness

    Now include the relevant CSS in your app view.yml:

    stylesheets: [main, smoothness/jquery-ui-1.7.1.custom.css]

    5. Setup the Widget your form class:
    Note in my example below, I will have an image icon as the date selector (/images/icons/calendar_view_month.gif). This is what the form class will look like:

    class myForm extends sfForm {
      public function configure()
      {
        $this->setWidgets(array(
          'from_date'    => new sfWidgetFormJQueryDate(array(
                 'image'=>'/images/icons/calendar_view_month.gif', 
                 'format' => '%day%/%month%/%year%')
                 ),
         //...other widgets
        ));
     
        $this->widgetSchema->setLabels(array(
      		'from_date'    => 'From Date',
                    //...other labels
        ));
      }
    }

    6. Display it in your view:
    Action:

      public function executeSearch(sfWebRequest $request){    
        $this->form = new myForm();
        return sfView::SUCCESS; 
      }

    View:

    ....
    echo $form['from_date']->renderLabel().":".$form['from_date'];
    ....

    And that’s it! You should get something looking like this:

    Hope this helps.

    Looking for Symfony Plugins…

    I was working on a project that I decided could do with some client side AJAX validation…. So a bit of digging around led me to sfYzAjaxValidationPlugin… I quickly found out that the old plugin faq’s now redirect to the new plugin site… The only problem was, the plugin I was after, and it seems a lot of other plugins, haven’t been migrated over yet.

    My forum post about it went unanswered, but last night I came across a post from Fabien in the symfony google group noting that for a limited time only, the old plugins site is available here : http://raw.trac.symfony-project.org/wiki/SymfonyPlugins

    Hopefully that will help others out looking for plugins that for whatever reason aren’t on the new site yet.

  • 1 Comment
  • Filed under: plugins
  • Today the guys at the Symfony Project announced plugins have a new home. Symfony Plugins.


    Symfony Plugins

    It’s great. Some great new features:

  • Each plugin has a dedicated page
  • Plugin developers have their own admin console to manage the plugin details - this will be great for the community
  • Each plugin clearly identifies which version its compatible with
  • This will help the developer community to get together and start contributing as one. It’s similar to Ubuntu Launchpad - not quite as advanced, but with the new introduction of developers being able to own plugins and contribute in such a clear way - its going to be a great addition to the community.

    The Beauty of sfPropelFinder

    I was just catching up on my feeds this morning, and came across an update on another great piece of workby Francois.

    The easiest way to explain what I like about this plugin is just to look at the following example… it is in another class for ease of readability and simplicity in writing compared to the ’standard’ symfony method:

    // With Peer and Criteria
    $c = new Criteria()
    $c->add(ArticlePeer::TITLE, ‘%world’, Criteria::LIKE);
    $c->add(ArticlePeer::IS_PUBLISHED, true);
    $c->addAscendingOrderByColumn(ArticlePeer::CREATED_AT);
    $articles = ArticlePeer::doSelectJoinCategory($c);


    // with sfPropelFinder
    $articles = sfPropelFinder::from('Article')->
    where('Title', 'like', '%world')->
    where('IsPublished', true)->
    orderBy('CreatedAt')->
    with('Category')->
    find();

    Check it out here.

    Wow, I’m blown away with how easy it is to get some pagination going with Symfony. In my previous life, I had coded my own custom Pagination class - it would have been easily 100 lines of code. I’ve just implemented some very basic pagination with less than 20 lines of code.

    I’m assuming you have created your model objects, and have a basic setup going. Im also doing this in Symfony 1.0. Lets now go ahead and create some basic pagination.

    1. Edit your actions.class.php for the module you want to paginate. In my case, I want to create a listing of all companies. For this, I’ll have a executeList action within that class. Here is what it looks like:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    class companyActions extends sfActions
    {
      ...
      public function executeList(){
        //Get a listing of all companies
        $this->companys = CompanyPeer::doSelect(new Criteria());
     
        //Lets do the pagination for it, firstly define a pager for the Company object. Lets go with 10 results per page
        $pager = new sfPropelPager('Company', 10);
        //Define the criteria, in this case, we won't have any - lets get all companies 
        $pager->setCriteria(new Criteria());
        //Set the first page to 1
        $pager->setPage($this->getRequestParameter('page', 1));
        $pager->init();
        $this->pager = $pager;
      }
       ...
    }//class

    2. Now lets modify your view for listSuccess.php to display what results you are viewing

    1
    2
    
    //Display a summary of the total companies found, and how many companies there are
    echo $pager->getNbResults()." Companies found. Displaying results ".$pager->getFirstIndice()." to ".$pager->getLastIndice();

    3. Now lets put in our main code to loop through the paginated results (still in listSucess.php)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    foreach ($pager->getResults() as $company){
        echo $company->getCompanyName();
         //go through and display all you want maybe in a nice table here
         //... 
    }
    //Now lets display a small navigation bar with arrows for next, previous and page numbers
    echo "<br/>";
      <?php if ($pager->haveToPaginate()): ?>
        <?php echo link_to('&laquo;', 'company/list?page='.$pager->getFirstPage()) ?>
        <?php echo link_to('&lt;', 'company/list?page='.$pager->getPreviousPage()) ?>
        <?php $links = $pager->getLinks(); foreach ($links as $page): ?>
          <?php echo ($page == $pager->getPage()) ? $page : link_to($page, 'company/list?page='.$page) ?>
          <?php if ($page != $pager->getCurrentMaxLink()): ?> - <?php endif ?>
        <?php endforeach ?>
        <?php echo link_to('&gt;', 'company/list?page='.$pager->getNextPage()) ?>
        <?php echo link_to('&raquo;', 'company/list?page='.$pager->getLastPage()) ?>
      <?php endif ?>

    That’s it! Now have a play with that, and if you are gaim, you could even go and do some Ajax Pagination or get some sorting going.

  • 17 Comments
  • Filed under: model, plugins, view