gpt4 book ai didi

php - Symfony 和 Bootstrap dateTimePicker : expected a string

转载 作者:搜寻专家 更新时间:2023-10-31 21:24:07 25 4
gpt4 key购买 nike

我正在尝试创建一个 DateTimePickerType 以轻松地将 Bootstrap dateTimePicker 添加到字段中,只需在表单生成器中使用类型“date_time_picker”即可。
不幸的是我遇到了一些问题。具体来说,Symfony 给我这个错误:

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.

很明显,我的表单正在向我的 Controller 发送 DateTime 对象, Controller 无法将其转换为字符串。在数据库中,该字段是日期时间类型。

这是我的 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';
}
}

我已经为解析器尝试了很多不同的选项。如果我删除“empty_data”中的“new\DateTime()”,我的表单现在发送一个 null 值,并且我在尝试将 null 插入数据库时​​收到一个很好的 SQL 错误。

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 %}

date_time_picker_script.html.twig 中:

{% autoescape false %}
<script type="text/javascript">
$(function () {
$('#date-time-picker-{{ id }}').datetimepicker();
});
</script>
{% endautoescape %}

我的 Form Builder 片段:

$builder
->add('startDate','date_time_picker')

提前致谢

编辑:刚刚注意到表单发送的日期时间忽略了我选择的内容,而是发送当前日期时间(当天、小时和分钟)。

最佳答案

显然这是因为需要在 PHP 和 JS 之间转换时间格式。我通过仅使用 DateType 解决了这个问题(时间不是必需的)。

这可能对那些仍然需要 DateTime 的人有用,但我还没有测试它:https://github.com/stephanecollot/DatetimepickerBundle

关于php - Symfony 和 Bootstrap dateTimePicker : expected a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40068650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com