I am trying to create a DateTimePickerType to easily add a Bootstrap dateTimePicker to a field, simply by using the type "date_time_picker" in the Form Builder.
Unfortunately I am running into some problems. Specifically, Symfony is giving me this error :
Symfony\Component\Validator\ConstraintViolation
Object(Symfony\Component\Form\Form).children[startDate] = Object(DateTime) - 2016-10-16T10:45:00+0200
Caused by:
Symfony\Component\Form\Exception\TransformationFailedException
Unable to reverse value for property path "startDate": Expected a string. Caused by:
Symfony\Component\Form\Exception\TransformationFailedException
Expected a string.
So apparently my form is sending a DateTime object to my Controller, who has trouble converting it to String. In the database, the field is of type datetime.
Here is my DateTimePickerType :
class DateTimePickerType extends AbstractType
{
/**
* @return string
*/
public function getParent()
{
return 'datetime';
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'empty_data' => new \DateTime(),
'widget' => "single_text",
'attr' => array(
'class' => 'addInput col-xs-12 dateSize noPadding noOutline dateTimePicker',
),
'format' => 'YYYY-MM-DD HH:mm',
'date_format'=>"dd/MM/yyyy hh:mm",
'html5' => false,
)
);
}
/**
* @param FormView $view
* @param FormInterface $form
* @param array $options
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars = array_replace($view->vars, array(
'empty_data' => $options['empty_data'],
'widget' => $options['widget'],
'format' => $options['date_format'],
));
}
/**
* @return string
*/
public function getName()
{
return 'date_time_picker';
}
}
I have tried many different options for the resolver. If I remove the "new \DateTime()" in "empty_data", my form now sends a null
value, and I get a nice SQL error trying to insert null into the database.
Snippet of form_template.html.twig :
{% block date_time_picker_widget %}
<div class='input-group date' id='date-time-picker-{{ id }}'>
<input type="text" class="form-control" />
<span class="input-group-addon"><i class="fa fa-clock-o"></i></span>
</div>
{% include 'VMSFormTypeBundle:Template:date_time_picker_script.html.twig' %} {# link to the direct js script to make it datetimepicker #}
{% endblock %}
In date_time_picker_script.html.twig :
{% autoescape false %}
<script type="text/javascript">
$(function () {
$('#date-time-picker-{{ id }}').datetimepicker();
});
</script>
{% endautoescape %}
Snippet of my Form Builder :
$builder
->add('startDate','date_time_picker')
Thanks in advance
EDIT : Just noticed the datetime that is sent by the form ignores what I select, and instead sends the current datetime (current day, hour and minute).