cake php auto select foreign keys when editing

309 views Asked by At

I am using Cake PHP with scaffolding. I'm having a problem with the code that it generates and want to see if there is a way around it of if I should end up building custom views.

Lets say that I have two models Tests and Questions. Tests can have many Questions and a Question has only one test. I have setup the hasMany and belongsTo Associations.

Now, the scaffolded view that cake creates for Tests gives me a button at the bottom in the "Related Questions" to create a question. When I click this button, I get the 'Add' form for questions, but the right test is not auto selected.

Is there anyway I can make the button pass the test_id into the Question form and have that auto populate?

3

There are 3 answers

0
Ross On

I see how you think that might work; but Cake doesn't know you want that behaviour out of the box.

You would need to adjust your Question Add method, or create a new one:

Example code:

// action: tests/view/1 (viewing test 1, and all related questions)
// create a link containing the ID of the current test as a param
<?php echo $this->Html->link('Add Question to Test', 
                                          array('controller'=>'questions',
                                                'action' => 'add_question',
                                                $test['Test']['id'])
                             );
?>

So - assuming you have access to id of the current test, you can pass it as a parameter to your questions controller (there are several ways to do this).

Then:

// view - questions/add_question/1
<h1>Adding A Question to Test 1</h1>
<?php 
// create your add question form

$this->Form->input('test_id', array('type'=>'hidden', 
                                  'value' => $this->params['pass'][0])); 
// create a hidden field with the value of the first passed param (the test id)

then in your controller, the test_id is already set, so when you save the question, it is saved with the appropriate test_id

0
Suman On

If you want to apply this to all your CakePHP projects generated using cake bake, you can make a couple of small changes to the CakePHP core to enable this, as seen here: https://github.com/srs81/cakephp/commit/7d92c8f676c79185fa6a74ab2070f240c555a2a0

Basically these two changes append the referring model/controller ID and name to the "add" action, and this is handled in the "add" action where the correct ID is selected.

This does NOT work for HABTM models, but should work fine for anything else.

0
ivandcl On

You need to add var $uses = array('Question','Test'); to questions_controller.php