Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right way to define and work with ENUM types from Symfony2 and Doctrine2

I'm using ENUM type in one of my tables but Doctrine doesn't like it so much. So I do my research and found this topic which basically talks about it. In this other doc from Doctrine project also talks about it and two possibles solutions. I'll use the first one but:

  1. Where it's supposed this code should go?

    $conn = $em->getConnection();
    $conn->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');

  2. How do I deal with this from Forms later when I want to display a SELECT with those values?

like image 298
Reynier Avatar asked Aug 05 '13 15:08

Reynier


2 Answers

Regarding this doc you need to add these lines to your config:

# app/config/config.yml
doctrine:
    dbal:
        connections:
            default:
                // Other connections parameters
                mapping_types:
                    enum: string

For the forms I'd add a helper like getPossibleEnumValues and use this to fill the choices in the builder:

$builder->add('enumField', 'choice', array(
    'choices' => $entity->getPossibleEnumValues(),
));
like image 140
althaus Avatar answered Sep 20 '22 15:09

althaus


You shouldn't use enum (for many reasons you can find on google or here), but if you absolutely want to use enum instead of a relation with another table the best way is to emulate the enum behavior like this :

<?php
/** @Entity */
class Article
{
    const STATUS_VISIBLE = 'visible';
    const STATUS_INVISIBLE = 'invisible';

    /** @Column(type="string") */
    private $status;

    public function setStatus($status)
    {
        if (!in_array($status, array(self::STATUS_VISIBLE, self::STATUS_INVISIBLE))) {
            throw new \InvalidArgumentException("Invalid status");
        }
        $this->status = $status;
    }
}
like image 41
Pierre Avatar answered Sep 21 '22 15:09

Pierre