I would like to update a form containing a date field. I can create the form with no problem but I could not edit it because I got an error. So here is my first class Contract:
<?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,
));
}
And here is my update code (Controller part):
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(),
));
}
The error I got:
Unable to transform value for property path "firstDay": Expected a \DateTimeInterface.
When I change line $serialize->deserialize ... with new Contract() it works, but I need to use serialize in order to use the same form.