0

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?

Teej
  • 12,764
  • 9
  • 72
  • 93
Lanbo
  • 15,118
  • 16
  • 70
  • 147

2 Answers2

1

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.

mirage
  • 111
  • 1
  • 11
0

First, both foreign keys for hasMany and belongsTo must be the same. If in the parent model you provided invoice_circle_id as the key, then the same must be provided in the child model also. Obviously, that field must exist in the child table. See this for more info http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

Second - you might want to use the saveAll() or saveAssociated() method for linked model data saving. Again - http://book.cakephp.org/2.0/en/models/saving-your-data.html contains all the ifnormation you need.

As for naming the input fields for hasMany, you name them like this:

$this->Form->input('ParentModel.fieldname');
$this->Form->input('ChildModel.0.fieldname');
Deez
  • 849
  • 2
  • 9
  • 28
  • I read that but I couldn't find how it applies to my situation. I would have to write `$this->Form->input('State.' . $i . '.prefix_id');` for each `$state`? What will be put as a value? – Lanbo May 10 '13 at 09:17
  • Foreign key will be given automatically to each State, however, you need to give values to other State fields manually. – Deez May 10 '13 at 09:23
  • Ok, but the foreign key is the only value that I want to give the state fields... I think it's better to just manually set it on the controller. – Lanbo May 10 '13 at 09:29