【发布时间】:2016-03-18 13:49:29
【问题描述】:
所以,我有 3 个实体。所有都是相关的,就像它显示在 picture
我在控制器中有这段代码
/**
* After clicking the link at our index page we are getting to the show page
* where the user can pass the test
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
// Here we get out test's ID
$test = $em->getRepository('TestprojectTestManagerBundle:Test')->find($id);
// Then we get our questions information according to previously chosen test's ID
$questions = $em->getRepository('TestprojectTestManagerBundle:Question')->findBy(
array('test'=>$test),
array('question'=>'ASC')
);
// Here I tried to do the same with my answers, i.e. getting answers according to the current question
// But faild. $questions is all questions of our test. So, we get all answers of all questions of our test.
// Didn't figured out how to solve this.
$answers = $em->getRepository('TestprojectTestManagerBundle:Answer')->findBy(
array('questions'=>$questions),
array('answer'=>'ASC')
);
return $this->render('TestprojectTestManagerBundle:Test:show.html.twig', array(
'test'=>$test,
'questions'=>$questions,
'answers'=>$answers,
));
}
然后我尝试在 show.html.twig 中创建一个页面
<ul>
{% for question in questions %}
<li>
<p>{{ question.question }}</p>
{% if question.toa == 'select' %}
<form>
{% for answer in answers %}
<input type="radio" name="answer" value="{{ answer.answer }}">{{ answer.answer }}</input><br>
{% endfor %}
</form>
{% endif %}
{% if question.toa == 'check' %}
<form>
{% for answer in answers %}
<input type="checkbox" name="answer{{ answer.id }}" value="{{ answer.answer }}">{{ answer.answer }}</input><br>
{% endfor %}
</form>
{% endif %}
{% if question.toa == 'textfield' %}
<form>
{% for answer in answers %}
<input type="text" name="answer{{ answer.id }}"><br>
{% endfor %}
</form>
{% endif %}
</li>
{% endfor %}
</ul>
所以,我期待得到这样的东西:
Test1
Question 1
Q1.Answer 1
Q1.Answer 2
Question 2
Q2.Answer 1
Q2.Answer 2
但我明白了
Test1
Question 1
Q1.Answer 1
Q1.Answer 2
Q2.Answer 1
Q2.Answer 2
Question 2
Q1.Answer 1
Q1.Answer 2
Q2.Answer 1
Q2.Answer 2
如何根据相关的 question_id 显示我的答案? 我还尝试调用 question_id 并尝试在我的 twig 模板中创建一个 if 语句。就像如果 question.id == answer.question_id 然后显示 answer.answer。但它没有用。它说 question_id 不存在。虽然它存在于我的数据库中! 在我的实体中有:
//in answer entity
/**
* @ORM\ManyToOne(targetEntity="Question", inversedBy="answers")
* @ORM\JoinColumn(name="question_id", nullable=false, referencedColumnName="id")
*/
protected $questions;
//in question entity
/**
* @ORM\OneToMany(targetEntity="Answer", mappedBy="questions", cascade={"all"}, orphanRemoval=true)
*/
protected $answers;
所以,我尝试比较 question.id 和 answer.questions。但它说
在第 16 行的 TestprojectTestManagerBundle:Test:show.html.twig 中的模板呈现期间引发了异常(“注意:Testproject\TestManagerBundle\Entity\Question 类的对象无法转换为 int”)。
我也尝试了 {% if question.answers == answer.questions %},它让渲染顺利进行,但它返回 false。
有人有什么想法吗?谢谢你。 附:对不起我的英语。
【问题讨论】:
标签: php symfony collections