cybtow
cybtow

Reputation: 157

Doctrine 2: Save a 'date' field

I have this YAML definition entity:

Entity\Visit:
    type: entity
    table: visit
    fields:
        date:
            type: date
            id: true
        count:
            type: integer
            nullable: true
            options:
                unsigned: true
                default: 1

    lifecycleCallbacks: {  }

And the date field is created:

/**
 * @var \DateTime
 *
 * @ORM\Column(name="date", type="date")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="NONE")
 */
private $date;

If I try insert a new record in this way:

$date = new \DateTime('now');

$visit = new \Entity\Visit();
$visit->setDate($date);
$visit->setCount(1);
$em->persist($visit);
$em->flush();

I have this error:

ContextErrorException in UnitOfWork.php line 1413: Catchable Fatal Error: Object of class DateTime could not be converted to string

And I do it in this way:

$date = new \DateTime('now');
$date = $date->format('Y-m-d');

This error is shown:

FatalThrowableError in DateType.php line 53: Call to a member function format() on string

Can anybody help me in order to insert (or update) a 'date' field using Doctrine2? Thanks.

UPDATE: The field in database have to be a 'date' field.

Upvotes: 0

Views: 2332

Answers (2)

cybtow
cybtow

Reputation: 157

Finally, I have found the problem by myself: The problem is because of the primary key is a date column. It seems that Doctrine does not like those stuff.

My new YML file:

Entity\Visit:
    type: entity
    table: visit
    fields:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
            options:
                unsigned: true
        date:
            type: date
            unique: true
        count:
            type: integer
            nullable: true
            options:
                unsigned: true
                default: 1

    lifecycleCallbacks: {  }

Now, I can do this:

$date = new \DateTime('now');
$visit = new \Entity\Visit();
$visit->setDate($date);
$visit->setCount(1);
$em->persist($visit);
$em->flush();

Upvotes: 1

Jigar Pancholi
Jigar Pancholi

Reputation: 1249

Please try with below code:

$date = new \DateTime();

$visit = new \Entity\Visit();
$visit->setDate($date->format('Y-m-d'));
$visit->setCount(1);
$em->persist($visit);
$em->flush();

Upvotes: 0

Related Questions