Use utf8 in Symfony with Doctrine

Here we will see how to configure Doctrine to use utf8 in Symfony.

So, we will set the charset and the collation of our database to use utf8, which most of the time is very useful, for instance, when we want to use a database with support to internationalization (i18N).

To do that we have three possibilities to see:

First, we can edit the config/ProjectConfiguration.class.php file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
class ProjectConfiguration extends sfProjectConfiguration
{
    public function setup()
    {
        $this->enablePlugins('sfDoctrinePlugin');
    }

    public function configureDoctrine(Doctrine_Manager $manager)
    {
        $manager->setCollate('utf8_unicode_ci');
        $manager->setCharset('utf8');
    }
}

The second one is to set the configuration in the config/databases.yml file:

1
2
3
4
5
6
7
8
9
10
11
all:
  doctrine:
    class: sfDoctrineDatabase
    param:
      dsn:      mysql:host=localhost;dbname=myDatabase
      username: myUser
      password: mySecret
      attributes:
        default_table_type:    InnoDB
        default_table_collate: utf8_unicode_ci
        default_table_charset: utf8

And the last one is to set the options in our schema (config/doctrine/schema.yml):

1
2
3
4
options:
  collate: utf8_unicode_ci
  charset: utf8
  type: InnoDB

I hope this is helpful for you.

share it...Share on FacebookTweet about this on TwitterShare on LinkedInShare on Google+Pin on PinterestDigg thisEmail this to someone

4 Comments

  1. Very good tip, I was stopped on this, but I have a question, my tables and fields are created successfully with utf8, using the second option of modify the databases.yml file, but the database is still create it with latin1, I can change it manually but I want to know if someone knowns how to configure it automatically with Symfony. I repeat myself, it is only to improve it, it’s working fine so far.

    Reply

Leave a Comment.