Reputation: 24985
Short Version:
Does anyone know how to do a simple date insert using Doctrine2? I need to insert a date in the format YYYY-MM-DD ('Y-m-d') into a MySQL 'date' field.
If you already know how to do this, you can probably skip the explanation below of what I've tried so far. Otherwise, more details about my problem follow below the break.
Long Version:
I have a Doctrine2 CRUD application and need to insert a form-submitted date into a MySQL database.
The date is submitted in a form using three dropdown menus: Year, Month, and Day.
In my Doctrine repository method, I use date() to convert the submitted values into a date and then invoke a method named setCreated() in my entity class:
$string = $values['year'] . '-' . $values['month'] . '-' . $values['day'];
$date = date('Y-m-d', strtotime($string));
$item->setCreated($date);
Then in setCreated(), first I tried to pass in the date like this:
public function setCreated($date) {
$this->created = $date;
}
But that gives me this error message: "Call to a member function format() on a non-object in ...Doctrine\DBAL\Types\DateType.php".
Next I tried altering the setter like this:
public function setCreated($date) {
$this->published = new \Doctrine\DBAL\Types\DateType($date);
}
But this doesn't work either: "Call to private Doctrine\DBAL\Types\Type::__construct()..."
Finally I tried creating a simple Date object to insert:
public function setCreated($date) {
$this->created = new \Date($date);
}
That gives me this error: "Class 'Date' not found in Path\To\Entity\Item.php..."
I also tried the above version without the leading backslash for Date, which gives me this error: "Warning: require(Path\Entity\Date.php) failed to open stream. No such file or directory in Path\Doctrine\Common\ClassLoader.php..."
(To confirm, my include paths are configured properly in php.ini -- specifically the include_path \php\PEAR
which is where Date.php is located.)
There's an explanation in the Doctrine manual about working with DateTime instances, but I don't need to store the time, just the date as YYYY-MM-DD.
This seems like it would be a pretty common issue - does anyone see what I'm doing wrong and/or know how to do a date insert in Doctrine2?
Upvotes: 3
Views: 4914
Reputation: 6712
Just add a constructor into Your class (to set default date). If You want to set Your own date, just modify this code and use it in setDateField() method likewise:
public function __construct() {
$this->date_field = new DateTime();
}
Upvotes: 2
Reputation: 197658
You care too much about your database. Just create the DateTime
instance and assign it as value to the object property which is of type DateTime
.
The database will store it as you have defined it, so no worries.
And if you format it back to a YYYY-MM-DD
formatted string value, you will see it did store.
Doctrine is to abstract away from your concrete database, so don't worry so much about your database when you use it.
Upvotes: 8