mctedo
mctedo

Reputation: 45

CakePHP Automagic Form Helper with Associations

I have two CakePHP models, Tests and Questions, where a Test has many questions, and a Question only has one test.

Neither this code:

echo $form->create("Question", array('action' => 'add'));
echo $form->input("text");
echo $form->input("Test.id", array( 'value' => $test['Test']['id']  , 'type' => 'hidden') ); 
echo $form->end("Add");

Nor:

echo $form->create("Question", array('action' => 'add'));
echo $form->input("text");
echo $form->input("Question.Test.id", array( 'value' => $test['Test']['id']  , 'type' => 'hidden') ); 
echo $form->end("Add");

associates the new question with a test (but does create it in the database).

$test['Test']['id'] does produce a correct output of ID.

Assistance appreciated.

Upvotes: 0

Views: 1708

Answers (3)

Gus
Gus

Reputation: 16017

I know that this question is old, but for those who came here like me looking for CakePHP 3 answers, the association naming convention for inputs has changed, with table.field for BelongsTo/HasOne associations and tables.field for HasMany/BelongsToMany associations.

Read the docs for more info.

Upvotes: 0

entropid
entropid

Reputation: 6239

You should associate (if you haven't done it yet) the two models with hasOne and hasMany associations and doing so creating in the table questions a column called test_id (that's named foreignKey).

The form of the question then becomes:

echo $form->create("Question", array('action' => 'add'));
echo $form->input("text");
echo $form->input("Question.test_id", array( 'value' => $test['Test']['id']  , 'type' => 'hidden') ); 
echo $form->end("Add");

Upvotes: 1

Oldskool
Oldskool

Reputation: 34877

Your naming is off. You should call your hidden field Question.test_id instead, since that is the field where the value should be saved. For example:

$this->Form->input('Question.test_id', array('type' => 'hidden', 'value' => $test['Test']['id']));

Upvotes: 1

Related Questions