Category Archives: Uncategorized

Throwing errors on symfony forms

Se pretender associar um erro a um campo especifico num formulário. Crie um sfValidatorCallback onde valida o campo e desplota o erro para o campo referido.

1
2
3
4
5
if ($values['user'] == '')
{
    $error = new sfValidatorError($validator,'Invalid user.');
    throw new sfValidatorErrorSchema($validator, array( 'user' => $error));
}
1
2
echo $form['user'];
echo $form['user']->renderError();

Propel get average – mysql AVG

Here’s how to do it:

public function getAverageRating()

{
$c = new Criteria;
$c->addSelectColumn('avg(' . RatingPeer::RATING . ')');
$c->add(RatingPeer::ID, $this->getId());

$stmt = RatingPeer::doSelectStmt($c);
$average = $stmt->fetchAll(PDO::FETCH_COLUMN);
if(array_key_exists(0, $average)) {
return floatval($average[0]);
}
else
{
return 0;
}
}

Using CKEditor and CKFinder


+
  1. Download the sfCKEditorPlugin plugin
  2. Go to http://ckeditor.com/ and download the last version.
  3. Put the ckeditor folder to the webjs folder.
  4. Go to http://ckfinder.com/ and download the last version.
  5. Put the ckfinder folder to the webjs folder.
  6. Add sfCKEditorPlugin to the ProjectConfiguration.class.php
  7. Open app.yml (apps/frontend or backend/config..) and put:
      # sfCKEditorPlugin
      ckeditor:
        basePath: /js/ckeditor
      ckfinder:
        active: true
        basePath: /js/ckfinder
  8. Create config/autoload.yml:
    autoload:
      ckeditor:
        name:       ckeditor
        path:       %sf_web_dir%/js/ckeditor
        recursive:  on
        
      ckfinder:
        name:       ckfinder
        path:       %sf_web_dir%/js/ckfinder
        recursive:  on
  9. Add js files to the view.yml in this way:
    javascripts: [ckeditor/ckeditor.js, ckfinder/ckfinder.js]
  10. Edit /js/ckfinder/config.php… find CheckAuthentication() method and modify it toreturn true; however read the comments, it can be dangerous!
  11. Change the $baseUrl to /uploads/ckfinder/ in ckfinder’s config.php
  12. Type symfony cc to clear the cache.
  13. Use the following syntax to call CKEditor:
    $this->widgetSchema[‘my_editor’] = new sfWidgetFormCKEditor();

From: http://sakrawebstudio.blogspot.com/2010/10/install-ckeditor-and-ckfinder-in.html

Symfony a nossa missão

Qualquer departamento de IT, para ter sucesso, necessita de saber para que é que existe! À medida que um departamento cresce, essa necessidade é fundamental.
Também nós, GEEKS, chegamos a um consenso sobre a nossa MISSÃO.

Symfony Nosso que estais no svn,
santificado seja o vosso php,
vem a nós o vosso MVC,
seja feita a vossa aplicação
assim na terra como na web.

A cache nossa de cada dia nos daí hoje,
perdoai-nos os nossos bugs,
assim como nós perdoamos
ao Ti Nano,
não nos deixei cair em tentação
mas livrai-nos do Ruby.

Amém.

Décio @ Yammer

Distinct backend Filters for users

Simple way of showing different backend filters for different users:

lib/filter/doctrine/YourFormFilter.class.php

class YourFormFilter extends BaseYourFormFilter {
public function setup() {
// ...

$context = sfContext::getInstance(); /* @var $context sfContext */
$request = $context->getRequest(); /* @var $request sfWebRequest */
$user = $context->getUser(); /* @var $user sfBasicSecurityUser */

if ($user->hasCredential('credential_to_check')) {
$this->setWidget('your_field', new sfWidgetFormFilterInput());
$this->setValidator('your_field', new sfValidatorPass(array('required' => false)));
$this->widgetSchema->moveField('your_field', sfWidgetFormSchema::AFTER, 'other_field'); // this is good to re-arrange the filters order
}
}

// ...

Propel, extender schema de plugins

Quando precisamos de adicionar campos novos a uma tabela gerada por um plugin temos que criar um myPlugin_schema.custom.yml onde myPlugin é o nome do plugin.

Caso prático: Adicionar o campo ‘coisas’ na tabela sf_guard_user (gerada pelo plugin sfGuardPlugin)

1 – criar o ficheiro sfGuardPlugin_schema.custom.yml em project/config/

propel:
_attributes: { package: plugins.sfGuardPlugin.lib.model }

##
# extending sfGuard
##
sf_guard_user:
_attributes: { phpName: sfGuardUser }
coisas: { type: varchar, size: 128, required: true }

2 – fazer re-build das classes

php symfony propel:build --all-classes

Done!

Servir documentos através de uma action

Por vezes, torna-se necessários servir ficheiros privados, que em vez de estarem no diretório público web/uploads, devem ficar fora de web, impedindo o acesso direto, cabendo a uma action verificar se o utilizador tem permissões e então entregar o ficheiro. Eis como o fazer através do object sfResponse numa action:

public function executeBackup(sfWebRequest $request)
{
// realizar backup da base de dados e dos uploads
$this->setLayout(false);
$this->setTemplate(false);
sfConfig::set(‘sf_web_debug’, false);

// nome do ficheiro tem de coincidir com o definido na task uacBackupTask
$file_cache = sfConfig::get(‘sf_data_dir’).’/backup/backup_’.date(‘Y-m-d’).’.zip';
// verificar se existe ficheiro de backup criado pela task, se sim, entrega esse, senão gera novo
if (file_exists($file_cache))
{
$file = $file_cache;
}
else
{
$file = adcBackup::execute(); // cria o ficheiro e envia o caminho absoluto
$backup = sfConfig::get(‘sf_data_dir’).’/backup/’.basename($file);
@copy($file, $backup);
@chmod($backup, 0666);
}

// check if the file exists
$this->forward404Unless(file_exists($file));

// Adding the file to the Response object
$this->getResponse()->clearHttpHeaders();
$this->getResponse()->addCacheControlHttpHeader(‘Cache-control’,’must-revalidate, post-check=0, pre-check=0′);
$this->getResponse()->setHttpHeader(‘Pragma: public’, true);
$this->getResponse()->setContentType(‘application/zip’);
$this->getResponse()->setHttpHeader(‘Content-Disposition’,’attachment; filename=’.basename($file), true);
$this->getResponse()->sendHttpHeaders();
$this->getResponse()->setContent(file_get_contents($file));

return sfView::NONE;
}

symfony & Doctrine behavior review

The Doctrine ORM is bundled with several behaviors (calles core behaviors), these are:

  • Versionable – add an entire XxxVersion table to store your Xxx model object versions as either only version numbers or numbers versions along with ALL column data – to see object data changes through time,
  • Timestampable – probably the most popular of all behaviors, adds created_at and updated_at timestamp columns to your model, automatically saving datetime when a record is created or updated, respecticely,
  • Sluggable – adds a slug column that stores a slug which is a unique index automatically and can be used along with sfDoctrineRoute class to refer to an object without passing its ID as a parameter; by default the update is disabled, since this may harm your search engines rating,
  • I18n – add an entire XxxTranslation table to provide Internationalization (I18n) for your Xxx model, essential when developing a multi-language project,
  • NestedSet – adds root_id, lft, rgt and level columns to your model to develop an advanced hierarchical data structure (such as product categories), nested sets is an alternative to adjacency model, more details on hierarchical data here,
  • Searchable – choose model columns you want to index and add an entire database table, speeding up a basic search engine development, more info about searching here,
  • Geographical – adds longitude and latitude columns storing geographical coordinates. Ever needed to use gmaps in your project, along with sfEasyGMapPlugin? Not only this behavior suits the data structure you need, but also provides you with getDistance() method to calculate distance between two Geographical objects,
  • SoftDelete – adds a deleted_at column which defines if a record has been marked as deleted (and if so, when). Useful when designing a highly complicated system where data consistency is important and even if some data should be invisible in the backend, it should still remain in the database.

extension behaviors

You may also use Doctrine extensions:

  • Blameable – adds an additional level of auditing capabilities to models, blameable allows you to track who created or last updated any model in an environment with many users, blameable is a great companion to Timestampable behavior,
  • EventLoggable, readme – logs any Doctrine Events (pre/post Delete/Insert/…) fired upon a record, log type may be chosen (e.g. file) and events may be limited to the chosen ones only,
  • Localizable – gives you functionality to convert units of measurement (e.g. kilometers to miles, etc.) or any other conversions desirable,
  • Locatable – gives you functionality using the Google Maps API to automatically populate your model with latitude and longitide information using Google, a fantastic tool to use along with sfEasyGMapPlugin,
  • Sortable – gives you sortable functionality to your models, enabling you to easily fetch next/previous objects, moving them up/down in a sorted list or swapping with another object,
  • Taggable – adds Tagging capabilities, creates a TaggableTag table and a XxxTaggableTag table for each taggable model, using refClass m:n db table relation, provides easy tag management: add, remove, remove all, set, etc, finally, gives you the possibility to get the most popular tags (for a tag cloud, for example) fetched either from chosen models or from all of them,

plugin behaviors

Finally, there are also symfony plugins providing custom behaviors:

useful links about Doctrine behaviors:

http://symfony-world.blogspot.com/2010/10/symfonydoctrine-behavior-review.html