簡體   English   中英

參數1傳遞給?

[英]Argument 1 passed to?

我嘗試在symfony2.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;

請建議我如何解決此錯誤?

當您使用主義建立多對一關系時,保持此關系的屬性是相關實體的對象,而不是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

我認為問題在於$ 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);

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

問題是,通過使用原則設置關系,您聲明“ $ idCountry”是Country對象。

如果您設置idCountry本身,它將用作快捷方式(Doctrine允許您設置id而不是對象),盡管按照慣例,該屬性應命名為$ country,而不是$ idCountry,因為這樣做是為了抽象您您僅通過引用對象進行編碼時ID的存在情況。

之所以顯示此錯誤,是因為可能存在強制將其作為對象的類型提示,因此請在StudentRegistration類中查找類似以下內容的東西:

public function setIdCountry(MasterCountry $idCountry)

或類似的方法,如果希望能夠設置ID,則要刪除類型提示($ idCountry之前的MasterCountry)。 如果您不想觸摸它,則可能需要檢索國家對象並使用它,而不僅僅是ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM