Christopher Francisco
Christopher Francisco

Reputation: 16278

cakePHP association data form add

I'm using a simple association where an Item is classified in a Category. At the same time, an Item is made by a Brand. Until now I have 3 entities: Item, Category and Brand. So, for example, in my Item table I'd have category_id = 1, brand_id = 1.

So, reading the documentation, I understood that I should do the following:

class Item extends AppModel {
    public $hasOne = array('Category','Brand');
}

In the controller

public function add() {
    $this->set('categories', $this->Item->Category->find('list'));
    $this->set('brands', $this->Item->Brand->find('list'));
    //...

In the View

echo $this->Form->input('name');
echo $this->Form->input('description');
//...
echo $this->Form->input('Category');
echo $this->Form->input('Brand');

The issue is that the MySQL query executed attemps to create a row with the name, description, but not the category or brand. It looks like INSERT INTO Item('name',description') VALUES(.... no category or brand at all.

What am I doing wrong?

Upvotes: 0

Views: 53

Answers (1)

cornelb
cornelb

Reputation: 6066

You should change to

echo $this->Form->input('category_id');
echo $this->Form->input('brand_id');

The label names will still be Category and Brand, but the values will be saved

You should also change $hasOne with $belongsTo = array('Category','Brand');

Upvotes: 1

Related Questions