Automagic with related model data
I have a problem with automagic and related model data. I have 4 models: Exercice, Ecriture, Ligne, Compte. Exercice hasmany Ecriture and Ecriture hasmany Ligne and Compte hasmany Ligne in two relation given by to different foreign keys. I want to use automagic to populate my form. So using $this->data, I give this array to the view:
Array
(
[Exercice] => Array
(
[id] => 1
[theme] => marchandises
)
[Ecriture] => Array
(
[0] => Array
(
[id] => 1
[exercice_id] => 1
[numero] => 1
[enonce] => Quelle est la dincee?
[Ligne] => Array
(
[0] => Array
(
[id] => 1
[ecriture_id] => 1
[compte_debit_id] => 2
[compte_credit_id] => 1
[montant_debit] => 23
[montant_credit] => 23
[libelle] => Achat de marchandises
[student_id] => 1
[CompteDebit] => Array
(
[id] => 2
[nom] => achat marchandises
)
[CompteCredit] => Array
(
[id] => 1
[nom] => caisse
)
)
)
)
Now if I want to access to the first level I simply use:
$this->Form->input('Ecriture.0.enonce');
And everything works fine!
But I can't access the seconde level using:
$this->Form->input('Ecriture.0.Ligne.0.libelle');
Why is that so? Can开发者_开发技巧 somebody help me?
Try the following:
Within Controller:
$this->data = array(
'Exercice' => array('column1' => 'value1', 'column2' => 'value2', etc.),
'Ecriture' => array(0 => array('column1' => 'value1', 'column2' => 'value2', etc.)),
'Ligne' => array(0 => array('column1' => 'value1', 'column2' => 'value2', etc.)),
)
As you can see, what I'm proposing is to place the data for associated models in the same level and NOT nested one within the other. So, by this approach, you can set the form elements like: $this->Form->input('Exercice.column1');
or $this->Form->input('Ecriture.0.column1');
By the way, now that I think about it, you should be able to populate the $this->data
array automatically (for the form fields) by using read(), like: $this->data = $this->ModelName->read(null, $recordId)
. See more here in the cookbook.
精彩评论