我正在用Symfony制作一個應用程式。我得到了物體Answer和Question,它們是相關的。我想讓用戶將答案添加到問題中,但我遇到了一個問題,就是如何將question_id獲取到AnswerEntity。 下面是我想出的辦法。 Answer Controller
<?php
/**。
*回答控制器
*/
namespace AppController。
使用 AppEntityAnswer。
使用 AppEntityQuestion。
使用 AppFormAnswerType。
使用 AppRepositoryAnswerRepository。
使用 AppRepositoryQuestionRepository。
使用 SymfonyComponentFormExtensionCoreTypeFormType。
使用 SymfonyComponentHttpFoundationRequest。
使用 SymfonyComponentHttpFoundationResponse。
使用 KnpComponentPagerPaginatorInterface。
使用 SymfonyBundleFrameworkBundleControllerAbstractController。
使用 SymfonyFlexPackageFilter。
use SymfonyComponentRoutingAnnotationRoute。
/**。
* Class AnswerController.
*
* @Route("/answer")
*/
class AnswerController extends AbstractController
{
private $answerRepository;
private $answer;
private $paginator;
/**.
* AnswerController建構式
*
* @param AppRepositoryAnswerRepository $answerRepository 答案庫
* @param KnpComponentPagerPaginatorInterface $paginator
*/
public function __construct(AnswerRepository $answerRepository, PaginatorInterface $paginator)
{
$this-> answerRepository = $answerRepository;
$this-> paginator = $paginator;
}
/**。
* 索引動作。
*
* @param SymfonyComponentHttpFoundationRequest $request HTTP請求。
* @return SymfonyComponentHttpFoundationResponse HTTP回應。
*
* @Route(
* "/",
* methods={"GET"},
* name="answer_index",
* )
*/
public function index(Request $request, PaginatorInterface $paginator, AnswerRepository $answerRepository>)。) Response: Response?
{
$pagination = $paginator-> paginate(
$answerRepository->queryAll()。
$request->query->getInt('page', 1) 。
AnswerRepository::PAGINATOR_ITEMS_PER_PAGE
);
return $this-> render(
'answer/index.html.twig'。
['pagination' => $pagination].
);
}
/**。
* 創建動作。
*
* @param SymfonyComponentHttpFoundationRequest $request HTTP請求。
*
* @param AppRepositoryAnswerRepository $answerRepository 答案倉庫
*
* @return SymfonyComponentHttpFoundationResponse HTTP response
*
* @throws DoctrineORMORMException
* @throws DoctrineORMOptimisticLockException
*
* @Route(
* "/create",
* methods={"GET", "POST"},
* name="answer_create",
* )
*/
public function create(Request $request, AnswerRepository $answerRepository)。) Response: Response.
{
$answer = new Answer()。
$form = $this->createForm(AnswerType::class, $answer)。
$form-> handleRequest($request)。
if ($form->isSubmitted() && $form->isValid() ) {
$answer->setQuestion($this->getQuestion() )。
$answerRepository->save($answer) 。
$this->addFlash('success', 'answer_created_successfully') 。
return $this->redirectToRoute('answer_index')。
}
return $this-> render(
'answer/create.html.twig'。
['form' => $form-> createView()]
);
}
}
AnswerForm:
<?php
/**。
*回答型別。
*/
namespace AppForm。
使用 AppEntityAnswer。
使用 SymfonyBridge教義表單型別EntityType。
使用 SymfonyComponentFormAbstractType。
使用 SymfonyComponent表單擴展核心型別EmailType。
use SymfonyComponentFormExtensionCoreTypeHiddenType。
使用 SymfonyComponent表單擴展核心型別文本型別。
使用 SymfonyComponentFormFormBuilderInterface。
使用 SymfonyComponentOptionsResolverOptionsResolver。
/**。
*類AnswerType。
*/
class AnswerType extends AbstractType
{
/**。
* 構建表單。
*
* 這個方法是為層次結構中的每個型別呼叫的,從最上面的型別開始。
* 最上面的型別。型別擴展可以進一步修改表單。
*
* @see FormTypeExtensionInterface::buildForm()
*
* @param SymfonyComponentFormBuilderInterface $builder 表格生成器
* @param array $options 選項。
*/
public function buildForm(FormBuilderInterface$builder, array $options)。) void: $options.
{
$builder->add(
'AnswerText',
TextType::class,
[
'label' => 'label_answertext',
'required' => true,
'attr' => ['max_length' => 200] 。
]
);
$builder->add(
'Nick',
TextType::class,
[
'label' => 'label_nick',
'required' => true,
'attr' => ['max_length' => 64] 。
]
);
$builder->add(
'Email',
EmailType::class,
[
'label' => 'label_email'。
'required' => true。
'attr' => ['max_length' => 64] 。
]
);
$builder->add('is_best', HiddenType::class, [
'data' => '0',
]);
}
/**。
* 配置該型別的選項。
*
* @param SymfonyComponentOptionsResolverOptionsResolver $resolver 選項的決議器。
*/
public function configureOptions(OptionsResolver $resolver) 。void: $resolver.
{
$resolver->setDefaults(['data_class' => Answer::class])。
}
/**。
* 回傳此型別的模板塊名稱的前綴。
*
* 塊的前綴默認為下劃線的短類名,去掉 "Type "后綴。
* 去掉 "Type "后綴(例如:"UserProfileType" => "user_profile")。
*
* @return string 模板塊名稱的前綴
*/
public function getBlockPrefix()。string
{
return 'answer' 。
}
和AnswerEntity
<?php
namespace AppEntity;
使用 AppRepositoryAnswerRepository。
use DoctrineORMMapping as ORM;
/**。
* @ORMEntity(repositoryClass=AnswerRepository::class)
* @ORMTable(name="answer")
*/
class Answer
{
/**。
* @ORMId
* @ORMGeneratedValue
* @ORMColumn(type="integer")
*/
private $id;
/**。
* @ORMColumn(type="string", length=200)
*/
private $answer_text;
/**。
* @ORMManyToOne(targetEntity=Question::class, inversedBy="answer")
* @ORMJoinColumn(nullable=false)
*/
private $question;
/**。
* @ORMColumn(type="string", length=64)
*/
private $email;
/**。
* @ORMColumn(type="string", length=64)
*/
private $Nick;
/**。
* @ORMColumn(type="integer")
*/
private $isBest;
public function getId(): ?int
{
return $this->id。
}
public function getAnswerText(): ?string
{
return $this-> answer_text;
}
public function setAnswerText(string $answer_text) 。void
{
$this-> answer_text = $answer_text;
}
public function getQuestion(): ?Question?
{
return $this-> question;
}
public function setQuestion(? Question $question) 。void: ?
{
$this->question = $question;
}
public function getEmail(): ?string?
{
return $this->email。
}
title">setEmail(string $email) 。self
{
$this->email = $email;
return $this;
}
public function getNick(): ?string
{
return $this-> Nick;
}
public function setNick(string $Nick) 。self
{
$this-> Nick = $Nick;
return $this;
}
public function getIsBest(): ?int
{
return $this-> isBest。
}
title">setIsBest(int $isBest) 。self
{
$this->isBest = $isBest;
return $this;
}
該錯誤是。 [在此輸入圖片描述][1] 。 [1]: https://i.stack.imgur.com/fYGpo.png
但是我在AnswerEntity中有一個函式getQuestion,為什么它不讀這個函式呢?它讀取的是同一個物體的函式setQuestion。
是否有機會以另一種方式進行?
此外,我還添加了我的問題模板代碼的一部分,在那里我得到了create_answer
。 <a href="{{ url('answer_create', {id: questions.id}) }}" title="{{ 'create_answer'|trans }}" >
{{ 'create_answer'|trans }}}。
</a>
uj5u.com熱心網友回復:
答案就在你發布的錯誤圖片中,控制器中沒有$this->getQuestion(),除非你創建了這個函式。
你可以用Doctrine的任何識別符號來獲取問題物體
$question = this->getDoctrine()->getRepository(Question::class)->find($question_id) 。
然后你可以在你的$answer物件中設定問題關系
$answer->setQuestion($question) 。
uj5u.com熱心網友回復:
為什么你的路由中沒有questionId。我認為這是一個強制性的資料,可以知道用戶試圖回答哪個問題。
有了路由中的 requestParam id 和方法引數型別Question,ParamConverter 可以在你的控制器方法中注入正確的問題
/**.
* ...
* @Route(
* "/create/{id}"。
* methods={"GET", "POST"},
* name="answer_create",
* )
*/
public function create(Request $request, AnswerRepository $answerRepository, Question $question)。) Response{
$answer = new Answer()。
$answer->setQuestion($question)。
//....。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/310768.html
標籤:
