使用日期字段更新表单生成错误(symfony,php)

时间:2017-06-06 14:36:32

标签: php web-services symfony-3.2

我想更新包含日期字段的表单。我可以创建表单没有问题,但我无法编辑它因为我收到错误。所以这是我的第一堂课合同

<?php

 namespace AppBundle\Form;

use AppBundle\Entity\Contract;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

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 \AppBundle\DateTimeNormalizer(), $normalizer
                ), array (
                  $encoder
                  ) );
$headers = array('Accept' => 'application/json');
$response = Unirest\Request::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 = Unirest\Request::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. 

当我使用新的Contract()更改行$ serialize-&gt; deserialize ...时,它可以工作,但我需要使用序列化才能使用相同的表单。

1 个答案:

答案 0 :(得分:0)

尝试在

中使用DateTimeType课程代替DateType
$builder
    ->add('firstDay', DateType::class, array(
    'format' => 'yyyy-MM-dd',
  ))