2012-09-16 36 views
0

我試圖在symfony2.1中提交表單,但我得到以下錯誤,我創建了表單學生註冊並嘗試提交它,但我無法得到任何適當的解決方案。參數1傳遞給?

Error:Catchable Fatal Error: Argument 1 passed to 
Frontend\EntityBundle\Entity\StudentRegistration::setIdCountry() 
must be an instance of Frontend\EntityBundle\Entity\MasterCountry, string given, 
called in C:\wamp\www\careerguide\src\Frontend\HomeBundle\Controller\RegistrationController.php 
on line 41 and defined in C:\wamp\www\careerguide\src\Frontend\EntityBundle\Entity\StudentRegistration.php line 1253 

在控制我有:

$student_account = new \Frontend\EntityBundle\Entity\StudentRegistration(); 
$params = $request->get('student_registration'); 
$student_account->setIdCountry($params['idCountry']); 
$em = $this->getDoctrine()->getEntityManager(); 
$em->persist($student_account); 
$em->flush(); 

實體類:

/** 
* @var MasterCountry 
* 
* @ORM\ManyToOne(targetEntity="MasterCountry") 
* @ORM\JoinColumns({ 
* @ORM\JoinColumn(name="id_country", referencedColumnName="id_country") 
* }) 
*/ 
private $idCountry; 

請給我建議我做些什麼來解決這個問題?

回答

0

我認爲這個問題是$ PARAMS不是請求參數:

$params = $request->get('student_registration'); // looks like a String http param value 
$student_account->setIdCountry($params['idCountry']); //what could be $params['idCountry'] 

你或許應該想

$studentRegistrationId = $request->get('student_registration'); 
$studentRegistration = getStudentFromId($studentRegistrationId); // I don't know how you retrieve the $studentRegistration object 
$idCountry = $request->get('idCountry'); 
$student_account->setIdCountry($idCountry); 

我敢肯定,這不完全是,但對我來說,更有意義。

0

問題是,通過使用doctrine設置關係,您聲明「$ idCountry」是Country對象。

如果您設置了idCountry本身,它將作爲快捷方式(Doctrine允許您設置id而不是對象),但按照慣例,該屬性應該被命名爲$ country,而不是$ idCountry,因爲這個想法就是在你通過引用對象進行編碼的時候,把你的ID的存在抽象出來。

顯示此錯誤的原因可能有一種暗示迫使它爲對象,所以找的StudentRegistration類是這樣的:

public function setIdCountry(MasterCountry $idCountry) 

或類似的東西,你要刪除的類型 - 如果你想能夠設置一個id,請提示(MasterCountry $ idCountry之前)。如果你不想去觸摸它,那麼你可能需要檢索country對象並使用它來代替id。

1

當您使用doctrine建立多對一關係時,持有此關係的屬性是相關實體的對象,而不是id。它作爲一個id保存在數據庫中,但是Doctrine在你抓取它的時候會創建完整的對象,並且當你堅持它的時候會將這個對象轉換爲一個id。因此,爲了反映這一點,不應將該屬性稱爲$ idCountry,而應該使用$ country來代替(這不是強制性的,不過您可以調用它,但這樣可以使一切更加清晰)。 setter應該是setCountry(),它應該接受一個MasterCountry對象。

因此,當您從表單中接收到國家/地區ID時,應將其轉換爲MasterCountry對象(通過從數據庫中獲取),在studentRegistration中設置此對象,然後保留它。例如:

$student_account = new \Frontend\EntityBundle\Entity\StudentRegistration(); 
$params = $request->get('student_registration'); 
$country = $this->getDoctrine()->getRepository('AcmeStoreBundle:MasterCountry') 
     ->find($params['idCountry']); 
$student_account->setCountry($country); 
$em = $this->getDoctrine()->getEntityManager(); 
$em->persist($student_account); 
$em->flush(); 

儘管這應該起作用,但這不是Symfony處理表單的方式。您應該創建一個Form對象,然後綁定並驗證它。你不應該那麼必須處理的請求參數,等等。我建議你仔細閱讀Symfony的文檔本章:

http://symfony.com/doc/current/book/forms.html