1
我想更新包含日期字段的表单。我可以创建没有问题的表单,但由于发生错误,我无法编辑它。因此,这里是我的头等合同:用日期字段更新表单生成错误(symfony,php)
<?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.
当我更改行$ serialize->反序列化...与新的合同()它的工作原理,但我需要使用序列化,以使用相同的形式。
感谢您的想法@spiil我已经尝试过,但它不工作 – bsm