I am trying to make an Entity using a date as a primary key. The problem is that Symfony can\'t convert the DateTime I\'m using into a string to introduce it in the Identity
A roubust solution to this is to implement your own DBAL type, using a DateTime descendant with __toString() implemented:
format('c');
}
static function fromDateTime(\DateTime $dateTime) {
return new static($dateTime->format('c'));
}
}
class DateKeyType extends \Doctrine\DBAL\Types\DateType{
public function convertToPHPValue($value, \Doctrine\DBAL\Platforms\AbstractPlatform $platform) {
$value = parent::convertToPHPValue($value, $platform);
if ($value !== NULL) {
$value = DateKey::fromDateTime($value);
}
return $value;
}
public function getName()
{
return 'DateKey';
}
}
\Doctrine\DBAL\Types\Type::addType('datekey', 'DateKeyType');
//edit: do not forget this after creating entity manager.
//otherwise, you will get into problems with doctrine database diff / migrations.
$platform = $entityManager->getConnection()->getDatabasePlatform();
$platform->registerDoctrineTypeMapping('datekey', 'datekey');
$platform->markDoctrineTypeCommented(\Doctrine\DBAL\Types\Type::getType('datekey'));