Symfony2 Timestable trait: "Column 'createdAt' cannot be null" - php

I have a pretty standard Entity with the correct imports:
/**
* Budhaz\aMailerBundle\Entity\Instance
*
* #ORM\Table()
* #ORM\Entity
*/
class Instance {
use TimestampableEntity;
/** #ORM\Id #ORM\GeneratedValue #ORM\Column(type="integer") */
private $id;
...
}
But I would like to remove the createdAt (and updatedAt) from my form so the user don't and can't set them, so I remove it from the InstanceForm:
class InstanceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('startAt')
->add('endAt')
//->add('createdAt')
//->add('updatedAt')
->add('campaign')
;
}
...
}
But now I have this error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'createdAt' cannot be null
createdAt and updatedAt should automaticaly be set by Doctrine, but it stays null, anyone know why?

You have to set the values within the class manually. Then you can tell doctrine to set the new value before every update:
public function __construct() {
$this->setCreatedAt(new \DateTime());
$this->setUpdatedAt(new \DateTime());
}
/**
* #ORM\PreUpdate
*/
public function setUpdatedAtValue() {
$this->setUpdatedAt(new \DateTime());
}

app/config/config.yml
stof_doctrine_extensions:
orm:
default:
timestampable: true

You need to check if the bundle is installed. If not, run:
composer require stof/doctrine-extensions-bundle
It should create file: app/config/packages/stof_doctrine_extensions.yaml with the content:
stof_doctrine_extensions:
default_locale: en_US
orm:
default:
timestampable: true

Related

Doctrine doesn't map fields from FOSUserBundle and FOSOAuthServerBundle

I am using Symfony 2.8, FOSUserBundle 1.3 and FOSOAuthServerBundle 1.5
For all of the class needed to those Bundles to work, I ended up with doctrine not updating my schema properly. I mean it doesn't take into account the fields from the Base Class.
CREATE TABLE oauh2_access_tokens (id INT NOT NULL, client_id INT NOT NULL, user_
id INT DEFAULT NULL, PRIMARY KEY(id));
CREATE TABLE oauth2_auth_codes (id INT NOT NULL, client_id INT NOT NULL, user_id
INT DEFAULT NULL, PRIMARY KEY(id));
CREATE TABLE oauth2_clients (id INT NOT NULL, PRIMARY KEY(id));
CREATE TABLE oauth2_refresh_tokens (id INT NOT NULL, client_id INT NOT NULL, use
r_id INT DEFAULT NULL, PRIMARY KEY(id));
Here's my config:
doctrine:
orm:
#auto_generate_proxy_classes: "%kernel.debug%"
default_entity_manager: default
entity_managers:
default:
connection: default
naming_strategy: doctrine.orm.naming_strategy.underscore
mappings:
COMPANYAuthBundle: ~
fos_user:
db_driver: orm
firewall_name: api
user_class: COMPANY\AuthBundle\Entity\User
#FOSOAuthBundle Configuration
fos_oauth_server:
db_driver: orm
client_class: COMPANY\AuthBundle\Entity\Client
access_token_class: COMPANY\AuthBundle\Entity\AccessToken
refresh_token_class: COMPANY\AuthBundle\Entity\RefreshToken
auth_code_class: COMPANY\AuthBundle\Entity\AuthCode
service:
user_provider: fos_user.user_manager
And here's my class User
<?php
namespace COMPANY\AuthBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Entity\User as BaseUser;
/**
* Utilisateur
*
* #ORM\Table(name="users")
* #ORM\Entity
*/
class User extends BaseUser
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
// your own logic
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
}
So, yes I did put the right use and not FOS\UserBundle\Model\User as BaseUser;
Same thing for the class of OAuthServerBundle: (I'm just putting one here, they're all following the same pattern)
<?php
namespace COMPANY\AuthBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\OAuthServerBundle\Entity\Client as BaseClient;
/**
* Client
*
* #ORM\Table(name="oauth2_clients")
* #ORM\Entity(repositoryClass="COMPANY\AuthBundle\Repository\ClientRepository")
*/
class Client extends BaseClient
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
public function __construct()
{
parent::__construct();
}
}
Does anybody have an idea why base class' fields aren't put into my db? Thanks :)
Okay, I found the solution after 10 hours of search...
And the solution is to not forget to add FOSUserBundle and FOSOAuthServerBundle and all the base class bundles to your mapping.....
So this should be the config:
doctrine:
orm:
#auto_generate_proxy_classes: "%kernel.debug%"
default_entity_manager: default
entity_managers:
default:
connection: default
naming_strategy: doctrine.orm.naming_strategy.underscore
mappings:
COMPANYAuthBundle: ~
FOSUserBundle: ~
FOSOAuthBundle: ~
Also, you can't make a bundle inherit from two bundles if you want to use the routes of each. So, create one bundle for each. Then in each of the Bundle class, add the following function:
public function getParent()
{
return "FOSOAuthServerBundle"; //Or return "FOSUserBundle"; but you can't put both
}

Symfony SoftDeleteable

I have entity and I use
* #Gedmo\SoftDeleteable(fieldName="deletedAt")
and when I delete some entity in my database I have my entity and in field deletedAt I have time when I delete entity and this is ok. But Now I need find all deleteAt entity? I create QB
$qb = $this->getEntityManager()->createQueryBuilder('d');
$qb
->select('d')
->from('ArtelProfileBundle:Project', 'd')
->where('d.deletedAt IS NOT NULL');
$count = $qb->getQuery()->getResult();
$query = $qb->getQuery();
$results = $query->getResult();
return [$results, $count];
I have 0 entity, why and how find entity ?
UPDATE
In my controller
class ProjectController extends FOSRestController
{
public function getProjectsAction(ParamFetcher $paramFetcher)
{
$manager = $this->getDoctrine()->getManager();
if($paramFetcher->get('status'))
{
$manager->getFilters()->disable('soft-deleteable');
$queryBuilder = $manager->getRepository('ArtelProfileBundle:Project')->findForStatusProject($paramFetcher, $this->getUser());
}
and I have error
Filter 'soft-deleteable' is not enabled.
my entity
/**
* Project
*
* #ORM\Table(name="project")
* #Gedmo\SoftDeleteable(fieldName="deletedAt")
* #ORM\Entity(repositoryClass="Artel\ProfileBundle\Entity\Repository\ProjectRepository")
* #ExclusionPolicy("all")
*/
class Project
{
/////
/**
* #var \DateTime $deletedAt
*
* #ORM\Column(name="deleted_at", type="datetime", nullable=true)
* #Type("DateTime")
* #Expose()
*/
protected $deletedAt;
help please
Solved
it is simply a mismatch between the name I use in my config and in my code
filters:
softdeleteable:
class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
enabled: true
stof_doctrine_extensions:
default_locale: "%locale%"
orm:
default:
timestampable: true
sluggable: true
softdeleteable: true
and then in my action I do
$manager->getFilters()->disable('softdeleteable');
And have the entity which I deleted
It's been a while, debugging the FilterColletion Class I found a simpler solution
$manager->getFilters()->disable('soft_deleteable'); //(using dash instead of minus sing, the last one is parsed to a dash )

Mapping Entity in CouchDb Symfony2

I'm using couchDb in symfony 2.7.2.
I have several doubts.
Now I installed this Bundle
And I create one entity for testing
<?php
namespace foo\GarageBundle\Document;
use Doctrine\ODM\CouchDB\Mapping\Annotations as CouchDB;
/**
* #CouchDB\Document
*/
class Utente
{
/** #CouchDB\Id */
private $id;
/** #CouchDB\Field(type="string") */
private $nome;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nome
*
* #param string $nome
* #return Utente
*/
public function setNome($nome)
{
$this->nome = $nome;
return $this;
}
/**
* Get nome
*
* #return string
*/
public function getNome()
{
return $this->nome;
}
}
In my controller I added this Code
$dm = $this->container->get('doctrine_couchdb.client.default_connection');
$doc = $this->container->get('doctrine_couchdb.odm.default_document_manager');
try{
$dm->createDatabase($dm->getDatabase());
}catch(\Exception $e){
$msg = $e->getMessage();
}
$user = new Utente();
$user->setNome('foo');
$doc->persist($user);
$doc->flush();
my config.yml is
doctrine_couch_db:
client:
default_connection: default
connections:
default:
dbname: symfony2
odm:
default_document_manager: default
document_managers:
default:
auto_mapping: true
With controller I created Database but I can't insert the new Document, I got this error
The class 'foo\GarageBundle\Document\Utente' was not found in the chain configured namespaces
And I don't understand why it is useful to use a bundle as what I am using ( I know it could be a stupid question ), and why I have to use * #CouchDB\Document instead of #Document inside my entity ?
Seems a problem related the namespace of the entity class.
The automapping is registering the CouchDocument subnamespace of
your bundle, not Document (which is auto-mapped by
DoctrineMongoDBBundle)
So use a different namespace for the User class and the other Counch you use, as follow:
namespace foo\GarageBundle\CouchDocument;
In particular:
<?php
namespace foo\GarageBundle\CouchDocument;
use Doctrine\ODM\CouchDB\Mapping\Annotations as CouchDB;
/**
* #CouchDB\Document
*/
class Utente
{
Hope this help
See this discussion on github.
/**
* #CouchDB\Document
* #CouchDB\Index
*/
class Utente
{

Symfony2 cannot find my doctrine2 entity class in the controller - how to fix?

I'm trying to run a simple SQL statement (something like select * from table) in my Symfony2 controller but it's not working. Somehow Symfony cannot find the class.
some info:
I've tried providing the full namespace + class name and just class name in the FROM clause
I've tried DQL and QueryBuilder (see code below. option1 and option2)
AppKernel is loading my DoctrineBundle. This was already there when I use composer to create my project
I've tried auto_mapping true and false in settings.yml
snippets of my codes are below
error message:
[Semantical Error] line 0, col 14 near 'Job j ORDER BY': Error: Class 'Job' is not defined.
500 Internal Server Error - QueryException
1 linked Exception:
QueryException »
[2/2] QueryException: [Semantical Error] line 0, col 14 near 'Job j ORDER BY': Error: Class 'Job' is not defined. +
[1/2] QueryException: SELECT u FROM Job j ORDER BY j.name ASC +
settings.yml
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
# if using pdo_sqlite as your database driver, add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/data/data.db3"
# path: "%database_path%"
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
#auto_mapping: false
#mappings:
# MyAppMyBundle:
# type: annotation
# dir: Entity/
my controller
<?php
// src/MyApp/MyBundle/Controller/JobsController.php
namespace MyApp\MyBundle\Controller;
use MyApp\MyBundle\Entity\Job;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class JobsController extends Controller {
public function listAction() {
$em = $this->getDoctrine()->getEntityManager();
//$qb = $em->createQueryBuilder();
//option1
//$qb ->select("j")
// ->from("Job", "j")
// ->orderBy("j.name", "ASC");*/
//return $this->render('MyBundle:Jobs:list.html.twig', array('jobs' => $qb->getQuery()->getResult()));
//option2
$qb = $em->createQuery("SELECT u FROM Job j ORDER BY j.name ASC");
return $this->render('MyBundle:Jobs:list.html.twig', array('jobs' => $qb->getResult()));
}
}
my entity class
<?php
// src/MyApp/MyBundle/Entity/Job.php
namespace MyApp\MyBundle\Entity;
use Doctrine\ORM\Mapping;
/**
* #Mapping\Entity
* #Mapping\Table(name="jobs")
*/
class Job {
/**
* #Mapping\Column(name="job_id", type="integer")
* #Mapping\Id
* #Mapping\GeneratedValue(strategy="AUTO")
*/
protected $jobId;
/**
* #Mapping\Column(name="name", type="text")
*/
protected $name;
/**
* #Mapping\Column(name="job_desc", type="text")
*/
protected $description;
/**
* #Mapping\Column(name="personal_req", type="text")
*/
protected $requirements;
/**
* Get jobid
*
* #return integer
*/
public function getJobId() {
return $this->applicationId;
}
/**
* Set name
*
* #param \text $name
* #return Job
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return text
*/
public function getName() {
return $this->name;
}
/**
* Set description
*
* #param \text $description
* #return Job
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return text
*/
public function getDescription() {
return $this->description;
}
/**
* Set requirements
*
* #param \text $requirements
* #return Job
*/
public function setRequirements($requirements) {
$this->requirements = $requirements;
return $this;
}
/**
* Get requirements
*
* #return text
*/
public function getRequirements() {
return $this->requirements;
}
}
use the full namespace if you make a query directly with entitymanager or just MyAppMyBundle:Job
be sure that your bundle is present in AppKernel
prefer to use $em->getRepository('MyAppMyBundle:Job')->createQueryBuilder('j') or $em->getRepository('MyAppMyBundle:Job')->findBy(array(),array('name' => 'ASC')
validate your model with php app/console doctrine:mapping:info and php app/console doctrine:schema:validate
Exceptions in symfony are always perfect so keep the focus on what your exception says
verify namespace of entity class. Because no generate error when write wrong namespace, but no find entity

Symfony2.1 mapping error: class_parents()

I have a problem trying to get data from a table (via entity) using Doctrine2 in a Symfony2.1 project. Here is the controller where I get the error:
/**
* Country list
*/
public function countrylistAction()
{
$em = $this->getDoctrine()->getManager();
$countryList = $em->getRepository('ProjectBaseBundle:SYS_TCountry')
->findAll();
$serializer = new Serializer(array(new GetSetMethodNormalizer()),
array('json' => new JsonEncoder()));
return new Response($serializer->serialize($countryList, 'json'));
}
The entity:
<?php
namespace Company\Project\BaseBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="SYS_TCountry")
*/
class SYS_TCountry
{
/**
* #ORM\Id
* #ORM\Column(type="string", length=3, nullable=false)
* #var string
*/
protected $idcountry;
/**
* #ORM\Column(type="string", length=75, nullable=false)
* #Assert\NotBlank()
* #var string
*/
protected $name;
....
public function getIdcountry() { return $this->idcountry; }
public function getName() { return $this->name; }
public function getA2() { return $this->a2; }
public function getA3() { return $this->a3; }
public function getIdstatus() { return $this->idstatus; }
public function setIdcountry($idcountry) { $this->idcountry = $idcountry; }
public function setName($name) { $this->name = $name; }
public function setA2($a2) { $this->a2 = $a2; }
public function setA3($a3) { $this->a3 = $a3; }
public function setIdstatus($idstatus) { $this->idstatus = $idstatus; }
public function __toString() { return $this->idcountry; }
}
Config.yml:
# Doctrine Configuration
doctrine:
dbal:
driver: %database_driver%
host: %database_host%
port: %database_port%
dbname: %database_name%
user: %database_user%
password: %database_password%
charset: UTF8
orm:
auto_generate_proxy_classes: %kernel.debug%
auto_mapping: true
And this is the error:
Warning: class_parents():
Class Company\Project\BaseBundle\Entity\SYS_TCountry does not exist and could not be loaded in
/var/www/project/src/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/RuntimeReflectionService.php line 40
It is strange because, as Doctrine says in console, the mapping is properly done: I test it executing php app/console doctrine:mapping:info:
[OK] Company\Project\BaseBundle\Entity\SYS_TCountry
and if I execute a query in console everything goes fine -> app/console doctrine:query:sql 'SELECT * FROM SYS_TCountry', that return results.
I do not know if using Symfony2.1 I have to configure something different to the 2.0 version, but seems the same because the mapping is Doctrine responsibility.
Symfony follows the PSR-0 standard for filenames. That, amongst other things, means that if you use an underscore in your class name, it will replace it with a directory separator when deciding where your class should live, like this:
\namespace\package\Class_Name => /path/to/project/lib/vendor/namespace/package/Class/Name.php
So, if you have a class named SYS_TCountry it would expect to find it in
Company/Project/BaseBundle/Entity/SYS/TCountry.php
instead of
Company/Project/BaseBundle/Entity/SYS_TCountry.php
I think that your best solution would be to change the filename and class name to SYSTCountry. You don´t need to change the table name.
Your class entity name is not compliant with PSR-0 which causes the loading error.
If you rename your entity to SYSTCountry everything will work fine!
Edit: Default Symfony2 and Doctrine autoloaders ARE PSR-0 compliant.

Categories