Search This Blog

Monday, February 4, 2013

Symfony 2 / Doctrine Support Enum Data types.

These posts were followed to add enum support to this Symfony 2 project:,
This post is to document the steps done to implement it, under Symfony 2.2.0

1. Add dbal configration in app/config/config.yml

        driver:   %database_driver%
        host:     %database_host%
        port:     %database_port%
        dbname:   %database_name%
        user:     %database_user%
        password: %database_password%
        charset:  UTF8
            enum: string
            enumservermonitor: JMPR\ServerMonBundle\Type\EnumServerMonitorType
            enumserverstatus: JMPR\ServerMonBundle\Type\EnumServerStatusType
            enumalertaction: JMPR\ServerMonBundle\Type\EnumAlertActionType

2. Create the column class types.

As specified in the config.yml file the Enum...Type classes are created.

The EnumServerMonitor type is below.
It does the following:
  • defines a classname and the enum values (service/website/host).
  • specifies the sql declaration.
  • defines 2 methods to convert the value to php from the database and from php to the database value.

namespace JMPR\ServerMonBundle\Type;

use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;

class EnumServerMonitorType extends Type
    const ENUM_SERVERMONITOR = 'enumservermonitor';
    const VALUE_SERVICE = 'service';
    const VALUE_WEBSITE = 'website';
    const VALUE_HOST = 'host';

    public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
        return "enum('service','website','host') NOT NULL default 'service' COMMENT '(DC2Type:enumservermonitor)'";

    public function convertToPHPValue($value, AbstractPlatform $platform)
        return $value;

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
        if (!in_array($value, array(self::VALUE_SERVICE, self::VALUE_WEBSITE, self::VALUE_HOST))) {
            throw new \InvalidArgumentException("Invalid monitor type");
        return $value;

    public function getName()
        return self::ENUM_SERVERMONITOR;

No comments:

Post a Comment