Question

I have a User Model and a Boarder Model, Not every User is a Boarder but Every Boarder is a User.

User model

class User extends AppModel
{
    public $primaryKey = "user_id";
    public $hasMany = 'Boarder';
}

Boarder model

class Boarder extends AppModel
{
    public $belongsTo = 'User';
}

add.ctp of my Boarders View

<?php 
echo $this->Form->create('Boarder', array('role' => 'form', 'novalidate' => true)); 
echo $this->Form->input('user_name');
echo $this->Form->input('bdr_home_address');
echo $this->Form->end();
?>

So during submit, add function in controller will now receive an array something like this

Array
(
    [Boarder] => Array
        (
            [user_name] => 'John',
            [bdr_home_address] => 'Some Street, Some City'
        )
)

[user_name] will be saved in Users Model while [bdr_home_address] will be saved in Boarders model. as indicated in my $this->Form->create the request will be directed to BoardersController, action add. So how will I be able to save this?

BoardersController

class BoardersController extends AppController
{
    public function add()
    {

    }
}
Was it helpful?

Solution

If every Boarder is a User, the Boarder table should include a user_id field.

The add.ctp form can look like

<?php
echo $this->Form->create('Boarder', array('role' => 'form', 'novalidate' => true));
echo $this->Form->input('User.username');
echo $this->Form->input('Boarder.home_address');
echo $this->Form->submit();
echo $this->Form->end();
?>

The add function from the controller is:

public function add()
{
    if ($this->request->is('post')) {
        debug($this->request->data);
        if ($this->Boarder->saveAssociated($this->request->data)) {
            // saved
        } else {
            // not saved
        }
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top