Nealv
Nealv

Reputation: 6884

Symfony datetime field with day and month optional

I have a symfony project with a doctrine entity that contains date fields. Everything works fine, but I want to be able to enter the day and month optionally. SO I can enter: 01-01-2014, or just 2014.

The widget exists of the standard 3 select fields. When I only enter the year field, it doesn't validate.

Is there a way to only enter the year ?

Upvotes: 2

Views: 1155

Answers (2)

piotr.gradzinski
piotr.gradzinski

Reputation: 923

I've faced the same problem. Within my application I have a date field with year and month, where month was optional. I've decided to do custom mapping type (http://symfony.com/doc/current/cookbook/doctrine/dbal.html#registering-custom-mapping-types, http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html#custom-mapping-types) and store those values as varchar in db. If search possibility is important I think this can be rewritten to store values as date, at least in MySQL, since you can store month and day as 00 (compare with https://stackoverflow.com/a/5882493/779084).

Below you can find code for Symfony 2.6.

https://gist.github.com/piotrgradzinski/2a2ba7c1a565dba723f6

Upvotes: 2

George
George

Reputation: 1499

In php, a date has a day, month, and year. You need to have all 3 to have a valid date. To accomplish your goal, I would suggest creating your own entity that has two fields - a date and a boolean. When you create a new object, set the date to Jan 1 and the boolean to false. If the user enters a date, change the boolean to true. This way even if the user wants to use Jan 1, you will know its a valid date because the boolean was changed.

The user does not need to see the boolean field either, just show them the month and date field and if they input any data, then change the boolean to true when you persist the object.

Upvotes: 1

Related Questions