我想更新包含日期字段的表单。我可以毫无问题地创建表格,但是我无法编辑它,因为我有错误。因此,这是我的第一类合同:
<?php
namespace AppBundleForm;
use AppBundleEntityContract;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyComponentFormExtensionCoreTypeDateType;
use SymfonyComponentFormExtensionCoreTypeTextType;
class ContractType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstDay', DateType::class, array(
'format' => 'yyyy-MM-dd',
))
->add('lastDay', DateType::class, array(
'format' => 'yyyy-MM-dd',
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Contract::class,
));
}
这是我的更新代码(控制器部分(:
public function updateAction($id, Request $request) {
$encoder = new JsonEncoder ();
$normalizer = new GetSetMethodNormalizer();
$callback = function ($dateTime) {
return $dateTime instanceof DateTime ? $dateTime->format ( 'Y-m-d' ) : '';
};
$normalizer->setCallbacks ( array (
'firstDay' => $callback
) );
$normalizer->setCallbacks ( array (
'lastDay' => $callback
) );
$serializer = new Serializer ( array (
new AppBundleDateTimeNormalizer(), $normalizer
), array (
$encoder
) );
$headers = array('Accept' => 'application/json');
$response = UnirestRequest::get('link/contracts/'.$id
,$headers);
$contract =
$serializer->deserialize($response->raw_body,Contract::class, 'json'); // Here when I dump my variable it appears good
$form = $this->createForm(ContractType::class,$contract); // In this line I got my error
$form->handleRequest($request);
if ($form->isSubmitted()) {
$headers = array('Content-Type' => 'application/json');
$data = $serializer->serialize($contract, 'json');
$response = UnirestRequest::put('link/contracts'.$id,
$headers,$data);
return $this->redirect ( $this->generateUrl ('contracts_list'));
}
return $this->render('AppBundle:Contract:ContractCreate.html.twig', array(
'form' => $form->createView(),
));
}
我遇到的错误:
Unable to transform value for property path "firstDay": Expected a DateTimeInterface.
当我更改行$ serialize-> delelialize ...使用新合同((起作用,但我需要使用序列化才能使用相同的形式。
尝试使用
中的DateTimeType
类而不是 DateType
$builder
->add('firstDay', DateType::class, array(
'format' => 'yyyy-MM-dd',
))