2013-03-03 78 views
1

我想用ajax調用上傳文件,但是當我去保存我的只保存與anagrafic的關係。 我聲明如果我試圖正常保存正常工作。Symfony2 Ajax上傳

就好像它沒有加載對象UploadFile! 我按照symfony的食譜http://symfony.com/doc/2.1/cookbook/doctrine/file_uploads.html 在我的控制器創建的表

public function fileCreateAction($id) 
{ 
    $em = $this->getDoctrine()->getManager(); 

    $entity = $em->getRepository('MyBusinessBundle:Anagrafic')->find($id); 
    $media = new Multimedia(); 
    $form = $this->createForm(new MultimediaType(), $media); 

    if ($this->getRequest()->isMethod('POST')) { 
     $form->bind($this->getRequest()); 
     if ($form->isValid()) { 
      $em = $this->getDoctrine()->getManager(); 

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

      $response = new Response(); 
     $output = array('success' => true); 
     $response->headers->set('Content-Type', 'application/json'); 
     $response->setContent(json_encode($output)); 
     } 
    } 

我試圖做的var_dump的後續代碼var_dump($媒體);並返回:

object(My\BusinessBundle\Entity\Multimedia)[337] 
    private 'id' => null 
    private 'percorso' => null 
    private 'alt' => null 
    private 'type' => null 
    public 'file' => null 
    private 'anagrafic' => null 

回答

0

我不明白爲什麼.. 但如果我用一個插件的jQuery https://github.com/blueimp/jQuery-File-Upload傳遞文件,我得到了正確的文件,我可以在食譜的方法繼續! 我的解決方案:

public function fileCreateAction($id) 
{ 
    $em = $this->getDoctrine()->getManager(); 

    $entity = $em->getRepository('MyBusinessBundle:Anagrafic')->find($id); 
    $media = new Multimedia(); 
    $form = $this->createForm(new MultimediaType(), $media); 

    $request = $this->getRequest(); 
    if ($request->isMethod('POST')) { 
     $form->bind($request); 
     if ($form->isValid()) { 
      $em = $this->getDoctrine()->getManager(); 
      $media->setAnagrafic($entity); 
      $em->persist($media); 
      $em->flush(); 

      if ($request->isXmlHttpRequest()) { 
       $response = new Response(); 
       $output = array('success' => true); 
       $response->headers->set('Content-Type', 'application/json'); 
       $response->setContent(json_encode($output)); 

       return $response; 
      } else { 
       return $this->redirect($this->generateUrl('user_img', array('id' => $entity->getId()))); 
      } 

    } else { 
    if ($request->isXmlHttpRequest()) { 
     $errors = $form->get('file')->getErrors(); 
     $response = new Response(); 
     $output = array('success' => false, 'errors' => $errors[0]->getMessage()); 
     $response->headers->set('Content-Type', 'application/json'); 
     $response->setContent(json_encode($output)); 

     return $response; 
    } 
    } 
    } 

將重構給出的兩個人通話 - > isXmlHttpRequest(),但這個概念的作品! 我忘了..如果您將輸入文件設置爲「多個」,則會爲每個文件發出一個請求!

解決!