Saving belongsTo models Cakephp
I have the following m开发者_如何转开发odel associations:
Question belongsTo Category
Category hasMany Question
Question hasMany Answer
Answer belongsTo Question
I want to be able to create a new category when creating a Question, but I am getting a Category.id
validation error, even though I am not sending setting the Category.id
in the $this->data
array. I successfully create new answers in the same form, but the Category is not being created.
My form:
<h3>Create multiple choice question</h3>
<?php
echo $this->Form->create('Question', array('action' => 'addmc'));
echo $this->Form->input('Question.name');
echo $this->Form->input('Question.questiontext', array('label' => 'Question Text (What students will see)'));
echo $this->Form->input('Question.generalfeedback', array('label' => 'General feedback (Feedback student will see when reviewing question)'));
for ($i = 0; $i < 4; $i++) {
echo $this->Form->input('Answer.'.$i.'.answer', array('label' => 'Answer ' . ($i+1)));
echo $this->Form->input('Answer.'.$i.'.score', array('label' => 'Score (Number from 0 to 100)'));
}
echo $this->Form->input('Category.0.name', array('label' => 'Category'));
echo $this->Form->button('Save question', array('class' => 'form'));
echo $this->Form->end();
?>
I am using saveAll in the controller. I tried by removing the validation rule for the Category.id
. The save operation went through but the category was not created.
in the controller, you need to save the category first, get that inserted id and assign to category_id in the question, then you can use saveAll on the question and answers.
If Question belongsTo Category, you probably have a Question.category_id field... That one should be used for chosing the category in a select box (at least, that's how I think you want it to work). The way you are trying to achieve this now doesn't make sense to Cake.
精彩评论