1

如果发生错误,我想在会话中保存表单数据,然后我可以在我的表单视图中显示有效的表单数据。

我有一个图像的文件字段,但是当我提交带有图像的表单时出现此错误:Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed

我的表格类型:

class ContenuType extends AbstractType
{
    private $session;

    public function __construct($session)
    {
         $this->session = $session;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $session = $this->session;
        $formSession = $session->get('dataCreateContenu');

        if (!$formSession) {
            $formSession = new Contenu();
        }
        $builder
        ->add('description', 'textarea', array(
                'label' => 'Description',
                'data' => $formSession->getDescription(),
                'attr' => array('maxlength' => 560),
                )
            )
        ->add('file', 'file', array(
                'label' => 'Image',
                'data' => $formSession->getImage(),
                'required' => false,
                )
            )
        ;
    }
}

我的表单控制器:

/**
 * New Contenu
 *
 * @Route("/", name="contenu_create")
 * @Method("POST")
 * @Template("MyOwnBundle:Contenu:new.html.twig")
 */
public function createAction(Request $request)
{
    $entity = new Contenu();

    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    $session = $this->get('session');
    $session->set('dataCreateContenu', $form->getData());

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        $formAll = $form->all();
        foreach ($formAll as $formField) {
            if(empty($formField->getData())) {
                $this->get('session')->getFlashBag()->add('error', 'Field « '.$formField->getConfig()->getOption("label").' » is empty.');
                return $this->redirect($this->generateUrl('contenu_new'));
            }
        }

        $image = $form->get('file')->getData();
        if ($image) {
            $entity->upload();// Upload
        }

        $em->persist($entity);
        $em->flush();

        $session->clear();

        return $this->redirect($this->generateUrl('contenu_show', array('id' => $entity->getId())));
    }

    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}

我能做些什么 ?

4

0 回答 0