Search code examples
phpcakephpforeign-key-relationshipmany-to-one

CakePHP to save relationship in other model


I have these models:

class Prefix extends AppModel {
    public $displayField = 'prefix';

    public $hasMany = array(
        'State' => array(
            'className' => 'State',
            'foreignKey' => 'prefix_id',
            'dependent' => false,
        ),
    );
}

class State extends AppModel {
    public $displayField = 'name';

    public $belongsTo = array(
        'Prefix' => array(
            'className' => 'Prefix',
            'foreignKey' => 'prefix_id',
        ),
    );
}

Then I have this admin_add method, from the automatic scaffolder:

public function admin_add() {
    if ($this->request->is('post')) {
        $this->Peefix->create();
        if ($this->Prefix->save($this->request->data)) {
            $this->redirect(array('action' => 'index'));
        } else {
                            // Error message
        }
    }
    $states = $this->Prefix->State->find('list');
    $this->set(compact('states'));
}

I also have the list of them in my form:

<?php echo $this->Form->input('State', array('multiple' => 'checkbox', 'type' => 'select',)); ?>

Now I can set the States for the Prefix. However, when I submit the form, the selection disappears. It is not saved in the database.

What did I do wrong?


Solution

  • You linked the models as if there is only one state per prefix, and many prefixes "assigned" to one state. That means you cannot use 'multiple' => 'checkbox'. So either remove this or change model associations to HABTM.