开发者

cakephp: cant pre-select a related model when adding

I think i've missed something. (cakephp)

I have a hasMany relationship from applicants to employers.And when i view an applicant, i see the related employers table all working perfectly (thanks to bake!)

But if i click 'New Employer', i want the applicants dropdown to pre-select so that i can hide it. i just cant figure out how i'd pass the applicant_id to the add view for employe开发者_StackOverflowrs.

(if i edit an employer from the related employers table for an applicant, the applicant_id does get passed)

Can anyone help? please? Vauneen


Simple. Pass the applicant_id to your employers/add action.

One way to do this is through URL parameters. Example: /employers/add/3 will pass "3" to the add action, and this could be taken as the applicant ID. Here's the controller code:

function add($applicantId = null) {
    // Optional: Check if $applicantId is provided
    if (!$applicantId) {
        $this->Session->setFlash('Applicant ID is missing.');
        $this->redirect(array('action' => 'index'));
    }
    // Process action
    if (!empty($this->data)) {
        $this->Employer->create();
        if ($this->Employer->save($this->data)) {
            // etc ...
        }
    } else {
        // Insert default values such as applicant_id into the form
        $this->data = array(
            'Employer' => array(
                'applicant_id' => $applicantId
            )
       );
    }
}

Now, you need to ensure that all links provide the applicant ID parameter:

echo $this->Html->link('Add Employer', array('controller' => 'employers', 'action' => 'add', 3);

(Note: The last element "3" is the applicant ID)

Finally, you can hide the applicant ID from the form in the add.ctp file:

echo $this->Form->input('applicant_id', array('type' => 'hidden'));

Hope that helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜