Dominykas55
Dominykas55

Reputation: 1231

Symfony2 Saving selected date from form to the database as DateTime

In my form a user selects when he would like to get the the purchase simply like this:

        ->add('start_date', 'date', array(
            'input'  => 'datetime',
            'widget' => 'choice',
        ))

Now I would like to save this date to the database in this field:

/**
 * @var \DateTime
 *
 * @ORM\Column(name="campaign_list_end_date", type="date", nullable=true)
 */
private $endDate;

So when the form is submited I get the date. But its an array of strings:

$data = $request->request->get('courier');
echo var_dump($data['start_date']); die;

array (size=3)
  'month' => string '2' (length=1)
  'day' => string '1' (length=1)
  'year' => string '2012' (length=4)

How can I convert this value to a DateTime object?

I tried something like this, it didnt work:

$date = new DateTime('now');
$start_date = $date->setTimestamp($data['start_date']);

Any ideas?

Upvotes: 0

Views: 575

Answers (1)

NDM
NDM

Reputation: 6830

When using symfony forms, you should retrieve the posted data from the form itself. The form will transform the data to the correct type for you:

$date = $form->get('start_date')->getData();

in addition, if your form is bound to an entity, you can also get the bound entity with the posted values extracted into it:

$entity = $form->getData();

Upvotes: 1

Related Questions