Tuesday, December 14, 2010

Get the Auto_increment value of a Table in MySQL

SELECT auto_increment 
FROM information_schema.tables 
WHERE table_name='the_table_you_want';

Sunday, December 12, 2010

Get the MySQL Configuration Parameters from databases.yml

MySQL configuration is stored in config/databases.yml. Use the code below to get the parameters in an action.
$databaseConf = sfYaml::load(sfConfig::get('sf_config_dir') . '/databases.yml');
$params   = $databaseConf ['all']['doctrine']['param'];
$dsn      = $params['dsn'];
$username = $params['username'];
$password = $params['password'];
$database = substr($dsn, strpos($dsn, 'dbname=')+7);
Only works if your dns parameter does not contain anything after the database's name, ex: dsn: mysql:host=localhost;dbname=thenameofthedatabase

Friday, November 19, 2010

Avoid Scrollbars when using JQuery Accordion

Use the fillSpace and clearStyle options and set them to TRUE.
    fillSpace: true,
    clearStyle: true

Saturday, November 13, 2010

Get the Language ID from Template in Joomla 1.5

$config = &JFactory::getConfig();

Tuesday, November 9, 2010

Get Raw Data in the Template in Symfony

echo $page->getRawValue()->getContent();
The $page variable is the model object and the getContent method gets the content column/text which contains HTML tags... To avoid html entities, you have to use the getRawValue method.

Friday, October 29, 2010

SQLSTATE[HY000]: General error: 1005 Can't create table

Let's see a very simple CORRECT relation and reasons why it can throw SQLSTATE[HY000]: General error...

      foreignAlias: Phonenumbers
      local: user_id
      foreign: id
      type: one
      foreignType: many

  1. Did you forget to define the user_id field in the Phonenumber table?
  2. Did you check the type of the user_id field and the Phonenumber table's id field? They must be exactly the same integer. If one of them is int(4) and the other is int(8), the building will fail.

Thursday, October 28, 2010

Remove PostValidator in Symfony

Remove post validator that is set in a base form:

$this->validatorSchema->setPostValidator(new sfValidatorPass()); 

Tuesday, October 26, 2010

generator.yml: Related Object's Fields in the DISPLAY List

If you want to show only the name (default field) of a related object, you can use the name of the object:

[id, name, Category]

This case Category will return with $this->getCategory()->getName() where $this is the current object. For other fields, create simple functions on the model class. Ex.:

// lib/model/doctrine/Article.class.php
public function getCategoryDescription()
  return $this->getCategory()->getDescription();

Now put this to the display list:

[id, name, category_description]

Wednesday, October 13, 2010

_csrf_token [CSRF attack detected.] error using sfAdminThemejRollerPlugin

If you try to do a batch delete with the Choose an option form, you can get a CSRF attack detection error using the sfAdminThemejRollerPlugin 0.2.0beta plugin.

  1.  Edit plugins/sfAdminThemejRollerPlugin/data/generator/sfDoctrineModule/jroller/template/templates/_list_batch_actions.php and change line 9 from:

    [?php $form = new sfForm(); if ($form->isCSRFProtected()): ?]


    [?php $form = new BaseForm(); if ($form->isCSRFProtected()): ?]
  2. Edit plugins/sfAdminThemejRollerPlugin/data/generator/sfDoctrineModule/jroller/parts/batchAction.php and change line 29 from:

    $validator = new sfValidatorDoctrineChoice(array('model' => '<?php echo $this->getModelClass() ?>'));


    $validator = new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => '<?php echo $this->getModelClass() ?>'));
  3. Type symfony cc to clear the cache.

Install CKEditor and CKFinder in Symfony

  1. Create the sfCKEditorPlugin folder in the Plugins folder.
  2. Download package: http://www.symfony-project.org/plugins/sfCKEditorPlugin
  3. Go to http://ckeditor.com/ and download the last version.
  4. Put the ckeditor folder to the web\js folder.
  5. Go to http://ckfinder.com/ and download the last version.
  6. Put the ckfinder folder to the web\js folder.
  7. Add sfCKEditorPlugin to the ProjectConfiguration.class.php
  8. Open app.yml (apps/frontend or backend/config..) and put:

      # sfCKEditorPlugin
        basePath: /js/ckeditor
        active: true
        basePath: /js/ckfinder
  9. Create autoload.yml file and put:

        name:       ckeditor
        path:       %sf_web_dir%/js/ckeditor
        recursive:  on
        name:       ckfinder
        path:       %sf_web_dir%/js/ckfinder
        recursive:  on
  10. Add  js files to the view.yml in this way:
    javascripts:    [ckeditor/ckeditor.js, ckfinder/ckfinder.js]
  11. Edit /js/ckfinder/config.php... find CheckAuthentication() method and modify it to return true; however read the comments, it can be dangerous!

    My solution: In production you will need to add a special cookie to the authenticated users, ex. imgupload... in this case you can use return isset($_COOKIE['imgupload']); in the function.
  12. Change the $baseUrl to /js/ckfinder/userfiles/ in config.php
  13. Type symfony cc to clear the cache.
  14. Use the following syntax to call CKEditor:
    $this->widgetSchema['my_editor'] = new sfWidgetFormCKEditor();
  15. I usually change the ckeditor interface. I remove the h1 tag and the unused functions. Try to put this to the ckeditor/config.js and refresh the browser window:

    CKEDITOR.editorConfig = function( config )
        //config.language = 'hu';
        config.format_tags = 'p;h2;h3;h4;h5;h6';
        config.height = 500;

        config.entities = false;
        config.disableNativeSpellChecker = false;
        config.scayt_autoStartup = false;

    CKEDITOR.config.toolbar_Full =
        ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'Templates'],

Friday, September 3, 2010

Convert Table Character Set in Mysql

for example...

Wednesday, September 1, 2010

How to Manage MySQL Table Names with #__ Prefix

Every time you make a query from a table that has a special #__ prefix, you need to put table name between `` signs.
INSERT INTO `#__session` ...
Otherwise it won't work and give you a meaningless error:

MySQL query error, please check your configuration! You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

Wednesday, August 25, 2010

sfDoctrinePager: Fatal error: Call to undefined method Doctrine_Collection::offset()

If you set a sfDoctrinePager object and give an EXECUTED query to the $this->pager->setQuery() method, you get a fatal error. Don't forget, sfDoctrinePager will execute the query, not you. Remove the ->execute() command from the end of the query.

Fatal error: Call to undefined method Doctrine_Collection::offset() in C:\webserv\www\phpcrm\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\pager\sfDoctrinePager.class.php on line 84

Text-Overflow in Table Cell

Really really long text to trim...

Friday, August 13, 2010

Download Files via Action in Symfony

public function executeDownload(sfWebRequest $request)
   $response = $this->getContext()->getResponse();
   $response->addCacheControlHttpHeader('Cache-control','must-revalidate, post-check=0, pre-check=0');
   $response->setHttpHeader('Content-Transfer-Encoding', 'binary', TRUE);
   $response->setHttpHeader('Content-Disposition','attachment; filename='.$request->getParameter('filename'), TRUE);
   return sfView::NONE;
This action requires a 'directory' and a 'filename' parameter.

Thursday, August 12, 2010

Old Nusoap Syntax can cause SOAP Error in PHP5

It is related to PHP5, which object names collides with the new soapclient() syntax (the PHP SOAP extension uses the same object name). If you change your syntax in the constructor from "new soapclient()" to "new nusoap_client()", the collision won't happen - and everything will be happy. Nusoap keeps the old syntax for legacy support ("new soapclient"). But PHP5 won't like it and give you a nice error:

Warning: SoapClient::SoapClient() expects parameter 2 to be array, boolean
given in /var/www/userdetails.php
on line 76

Fatal error: Uncaught SoapFault exception: [Client]
SoapClient::SoapClient() [soapclient.soapclient]: Invalid
parameters in
/var/www/userdetails.php:76 Stack
trace: #0
SoapClient->SoapClient('https://195.228...', true) #1
/var/www/index.php(48): include('/var/www/i...') #2
{main} thrown in
/var/www/userdetails.php on line 76

Wednesday, August 4, 2010

JSON Response in Symfony

If you want an action returns with json data, create something like this:
public function executeJson(sfWebRequest $request)
   // create the data
   $data = "something";
   return $this->renderText(json_encode($data));

Tuesday, August 3, 2010

Redirect to Referer in Action in Symfony


Validating Integers without Regular Expression in PHP

ctype_digit checks if all of the characters in the provided string are numerical. Therefore, you must convert variables to string first, then you check them with ctype_digit.
$array = array(5, 5.2, "456", "564-223", "5.2", "673");
foreach($array as $item) {
   if(ctype_digit((string)$item)) {
      echo "int: ".$item."\n";
   } else {
      echo "not int: ".$item."\n";

Monday, August 2, 2010

Delete embed forms/objects in Symfony

First of all, you have to add a delete checkbox to the embedded form:
// lib/form/doctrine/ formclass -> configure()
if ($this->object->exists())
   $this->widgetSchema['delete'] = new sfWidgetFormInputCheckbox();
   $this->validatorSchema['delete'] = new sfValidatorPass();
Don't forget to echo the 'delete' form widget in the template. Now open the form class which embed the other form. You have to overwrite some basic methods. The code below is used and created by me, but perhaps you won't be able to use/understand. Please, first check the the following blog entry: Embedding Relations in Forms with Symfony 1.3 and Doctrine
public function saveEmbeddedForms($con = null, $forms = null)
  if (null === $forms)
   $notes = $this->getValue('newNotes');
   $forms = $this->embeddedForms;
   foreach ($this->embeddedForms['newNotes'] as $name => $form)
    if (!isset($notes[$name]))
  foreach ($forms as $form)
    if ($form instanceof sfFormObject)
   if (!in_array($form->getObject()->getId(), $this->scheduledForDeletion))
   $this->saveEmbeddedForms($con, $form->getEmbeddedForms());

  protected function doBind(array $values)
    if (isset($values['Notes']))
      foreach ($values['Notes'] as $i => $noteValues)
        if (isset($noteValues['delete']) && $noteValues['id'])
          $this->scheduledForDeletion[$i] = $noteValues['id'];
  protected function doUpdateObject($values)
    if (count($this->scheduledForDeletion))
      foreach ($this->scheduledForDeletion as $index => $id)

Saturday, July 31, 2010

Disable HTML entities in CKEditor

Find ckeditor/ckeditor.config.js or ckeditor/config.js and add: config.entities = false;

Tuesday, July 27, 2010

Install AVR Media AUDIO and VIDEO Player for Joomla 1.5

  1. Install com_avreloaded-x.x.x.zip
  2. Check PHP upload_max_filesize setting, sometimes it has a very low value
  3. Go to Media Manager and create 'audio' and 'videos' folder in 'stories'
  4. Go to Global Settings and add the extensions (for uploading) you need (mp3, avi, mpg, etc)
  5. When you write an article, you will find an AVR Media button at the bottom, use that to include an audio or video player...

Thursday, July 15, 2010

Get User ID with Jumi in Joomla

If you include a php file to an article with Jumi, you can get the user id with this:
defined('_JEXEC') OR defined('_VALID_MOS') OR die( "Direct Access Is Not Allowed" );

$jAp= & JFactory::getApplication();
$user =& JFactory::getUser();
echo $user->get('id');

Tuesday, July 6, 2010

Select Items by the First Letter in MySQL

If you try to select items by the first letter and you want MySQL to deal with case sensitivity and accents, you have to collate the utf8_unicode_ci table to utf8_bin in this way...
SELECT * FROM thetable WHERE firstname COLLATE utf8_bin LIKE 'É%'

Thursday, June 24, 2010

Password Confirmation Widget and Validator in Symfony

$this->widgetSchema['password'] = new sfWidgetFormInputPassword(array('label' => 'Password'));
$this->widgetSchema['password_confirm'] = new sfWidgetFormInputPassword(array('label' => 'Password confirm'));
$this->validatorSchema['password'] = new sfValidatorString(array(
  'min_length' => 5
), array(
  'min_length' => 'Password too short (min 5 chars).'));
$this->validatorSchema['password_confirm'] = clone $this->validatorSchema['password'];
sfValidatorSchemaCompare::EQUAL, 'password_confirm', array(),
array('invalid' => 'Passwords do not match.')));
Note: In this case password fields are not required.

Wednesday, June 23, 2010

Create MySQL Dump to Save Data Before doctrine:build

If you use the symfony doctrine:build --all command, all data will be deleted in the database. To fix this, you have to save the data before the building and then import the dump file...
  1. mysqldump -t -c -u root -p DBNAME > dump.sql
  2. symfony doctrine:build --all
  3. mysql -u root -p DBNAME < dump.sql
Note: On Windows, you have to add the path (the mysql/bin directory) to the environmental variables.
Note2: The -t parameter removes the drop table and create table queries from the dump. It is needed if you change the structure of a table, otherwise drop table query will delete what symfony doctrine:build created.
Note3: The -c parameter adds the column names to INSERT INTO statements.

Tuesday, June 22, 2010

Enable mod_rewrite in Apache 2

Use the a2enmod rewrite command to enable mod_rewrite in Apache2, then restart the webserver with: /etc/init.d/apache2 restart

Monday, June 21, 2010

Symfony String Validator

$this->validatorSchema['subject'] = new sfValidatorString(array(
  'required' => true,
  'max_length' => 255
), array(
  'required' => 'Required field.',
  'max_length' => 'Too long, maximum 255 characters.'

Vertical Align in DIV

The container div must have these CSS properties:

display: table-cell;
vertical-align: middle;

and the child elements (img, div, span) must have only the vertical-align: middle; property.

Note: The container div mustn't have a float value!