2014-02-07 5 views
1

템플릿 엔진으로 Symfony2와 나뭇 가지를 사용합니다. 내 컨트롤러에서템플릿에 선택 필드를 렌더링하는 방법

나는 다음과 같은 형식이 있습니다

 $usr= $this->get('security.context')->getToken()->getUser();  
     $associatedmissions = array($usr->getMissions()); 

     $form = $this->createFormBuilder($product)   
     ->add('mission', 'choice', array(
      'choices' => $associatedmission, 
      'multiple' => false, 
      'expanded' => true,)) 

을하지만 페이지를 호출 할 때 오류가 나타납니다 :

: 나는 오류를 볼 수 있습니다

Catchable Fatal Error: Object of class Doctrine\ORM\PersistentCollection could not be 
converted to string in 
C:\BitNami\wampstack-5.4.23- 
0\frameworks\symfony\vendor\symfony\symfony\src\Symfony\Component\Translation\ 
IdentityTranslator.php line 65 

프로파일에서을

CRITICAL - Uncaught PHP Exception Twig_Error_Runtime: "An exception has been thrown 
during the rendering of a template ("") in "form_div_layout.html.twig" at line 99." at 
C:\BitNami\wampstack-5.4.23-0\frameworks\symfony\app\cache\dev\classes.php line 4372 

Context: {"exception":"Object(Twig_Error_Runtime)"} 

무슨 일이 일어 났습니까? 리디렉션을 사용하는

public function createAction(Request $request) 
    {           
     $product = new Product(); 

     $usr= $this->get('security.context')->getToken()->getUser();  
     $associatedmissions = array($usr->getMissions()); 

      $form = $this->createFormBuilder($product)          
      ->add('name', 'text') 
      ->add('mission', 'choice', array(
       'choices' => $associatedmissions, 
       'multiple' => false, 
       'expanded' => false,)) 

      ->add('save', 'submit') 
      ->getForm();  


     $form->handleRequest($request); 
     if ($form->isValid()) { 

     $em = $this->getDoctrine()->getManager();  
     $em->persist($product); 
     $em->flush(); 

     return $this->render('AcmeGroundStationBundle:Product:tasksuccess.html.twig', array('product' => $product)); 
     }  

     return $this->render('AcmeGroundStationBundle:Product:formupload.html.twig', array(
     'form' => $form->createView() 
     )); 
} 
+0

그리고'twig'에서 필드를 어떻게 렌더링하고 있습니까? –

+0

@Victor 이제'{{form_start (form)}} {{form_end (form)}}' –

+0

그냥'$ form-> createView()'와 같은'form' 변수를'return'에 나뭇 가지로 전달합니까 $ this -> render()'method? –

답변

1

aYou는 컨트롤러이 있습니다

$usr= $this->get('security.context')->getToken()->getUser();  
$associatedmissions = array($usr->getMissions()); 

$usr->getMissions()는 (당신의 엔티티에 관계 기준)의 ArrayCollection을 반환합니다. 이런 식으로 $associatedmissions은 관련된 임무 객체의 [1] = ArrayCollection이라는 하나의 요소가있는 배열입니다.

public function getMissionsArray() 
{ 
    $missionArray = array(); 

    foreach ($this->missions as $key => $val) 
    { 
     $missionArray[$key] = $val->__toString(); 
    } 
    return $missionArray; 
} 

을 그리고 당신의 createFormBuilder 문에 선택의 PARAM 같은 배열을 사용

내 생각에 당신은 당신의 사용자 개체 방법에 추가해야합니다.

양식의 유효성을 검사 할 때 영구 제품을 사용하기 전에 모든 선택 항목에 대해 Mission 개체를 만들어야합니다.

$this->getDoctrine() 
      ->getRepository('AcmeGroundStationBundle:Mission') 
      ->find($product->mission); 

편집

// User Entity 
// add this function - will return array of (id => mission.name,) 
public function getMissionsArray() 
{ 
    $missionArray = array(); 

    foreach ($this->missions as $key => $val) 
    { 
           // change this to whatever human readable getter 
     $missionArray[$key] = $val->__toString(); 
    } 
    return $missionArray; 
} 

// Controller  
public function createAction(Request $request) 
    {           
     $product = new Product(); 

     $usr= $this->get('security.context')->getToken()->getUser();  
     $associatedmissions = $usr->getMissionsArray(); 

      $form = $this->createFormBuilder($product)          
      ->add('name', 'text') 
      ->add('mission', 'choice', array(
       'choices' => $associatedmissions, 
       'multiple' => false, 
       'expanded' => false,)) 

      ->add('save', 'submit') 
      ->getForm();  


     $form->handleRequest($request); 
     if ($form->isValid()) { 

     // save selected array item as a Mission object related to Product 
     $product->setMission($this->getDoctrine() 
      // check if Mission Entity is placed in good bundle ;) 
      ->getRepository('AcmeGroundStationBundle:Mission') 
      ->find($form->get('mission')->getData())); 

     $em = $this->getDoctrine()->getManager();  
     $em->persist($product); 
     $em->flush(); 

     return $this->render('AcmeGroundStationBundle:Product:tasksuccess.html.twig', array('product' => $product)); 
     }  

     return $this->render('AcmeGroundStationBundle:Product:formupload.html.twig', array(
     'form' => $form->createView() 
     )); 
} 

행운을 빕니다!

+0

항상 준비와 가용성에 감사드립니다. 내 컨트롤러를 수정하는 방법을 이해하지 못했습니다. 또한 오류가 발생했습니다 : '개인 자산 Acme \ GroundStationBundle \ Entity \ Product :: $ mission'에 액세스 할 수 없습니다. –

+0

업데이트. 다음과 같이 : $ associatedmissions = $ this-> getDoctrine() -> getRepository ('AcmeManagementBundle : Mission') -> findAll ($ product-> mission); 다시 나는 모든 임무를 얻었고 관련 임무도 얻지 못했습니다. –

+0

내 대답을 확인하십시오. 전체 코드를 추가했습니다. – WebHQ

0

보십시오 : 그것은 여기에 제대로 내 컨트롤러를

-UPDATE--

->add('mission', 'entity') 
작동으로하기 때문에

이 이상하다. 작동합니까?

if ($form->isValid()) { 

     $em = $this->getDoctrine()->getManager();  
     $em->persist($product); 
     $em->flush(); 

     return $this->redirect($this->generatePath('current_route_name')); 
    } 

    return $this->render('AcmeGroundStationBundle:Product:formupload.html.twig', array(
     'form' => $form->createView() 
    )); 

여기에서 current_route_name은 현재 페이지의 경로 이름으로 대체됩니다.

+0

변경 사항 없음. 실제로 나는 또한 두 번째'render'를 리디렉션으로 대체하려고 시도했지만'Error : 정의되지 않은 메소드 호출 : generatePath'를 받았습니다. 'generateURL'을 사용하면''URL이 없습니다. 루프에서 리다이렉팅) –

+0

컨트롤러 클래스의 기본 심포니'Symfony \ Bundle \ FrameworkBundle \ Controller \ Controller'를 확장하고 있습니까? –

+0

예, 있습니다! Symfony \ Bundle \ FrameworkBundle \ Controller \ Controller를 사용하십시오; –

관련 문제