Ikong
Ikong

Reputation: 2570

CakePHP saving foreignKeys not working

I have 3 tables: Computers hasMany Brands, Brands belongsTo Computers and Parts. Now i have these fields in my Brands description,computer_id,part_id. I have the code below to save my data. It will save the description and part_id....But my computer_id does not save at all.

Usually my URL written http://192.168.6.253/computers/brands/add/1 where 1 is computer_id.

How will I save it? Im still beginner in this framework

Controller

public function add($id = null) {
            if (!$id) {
                throw new NotFoundException(__('Invalid post'));
            }
            //Assign value to link computer_id
            $data = $this->Brand->Computer->findById($id);
            $this->set('computers', $data);

            //assign select values to parts select
            $this->set('parts', $this->Brand->Part->find('list',
                array('fields' => array('description'))));


            if ($this->request->is('post')) {
                $this->Brand->create();
                if ($this->Brand->save($this->request->data)) {
                    $this->Session->setFlash(__('Your post has been saved.'));
                    $this->redirect(array('action' => 'table/'.$id));
                } else {
                    $this->Session->setFlash(__('Unable to add your post.'));
                }
            }

        }

View

<?php
echo $this->Form->create('Brand');
echo $this->Form->input('part_id',array('empty'=>' '));
echo $this->Form->input('description');
echo $this->Form->input('computer_id',array('type'=>hidden));
echo $this->Form->end('Save Post');
?>

Upvotes: 1

Views: 72

Answers (1)

Tim Joyce
Tim Joyce

Reputation: 4517

If you are not requiring to send the computer id through the form since it's a url param... you can adjust your add function like this

        if ($this->request->is('post')) {
            $this->request->data['Brand']['computer_id'] = $id; //manually add the id to the request data object
            $this->Brand->create();
            if ($this->Brand->save($this->request->data)) {
                $this->Session->setFlash(__('Your post has been saved.'));
                $this->redirect(array('action' => 'table/'.$id));
            } else {
                $this->Session->setFlash(__('Unable to add your post.'));
            }
        }

That's a very basic way of doing it without checking for data integrity, anyone could easily change the param to a 2, but it conforms with your current setup.

Upvotes: 1

Related Questions