In general, almost anytime you call FormHelper::input
, the first parameter will appear in one of the following formats:
- for the primary model, or
hasOne
and belongsTo
associations: $form->input('Model.field')
- for
hasMany
associations: $form->input("Model.{$n}.field")
- for
hasAndBelongsToMany
associations: $form->input("Model.Model.{$n}.field")
(In these cases, $n
is an iterator (0
,1
,2
,3
, etc.), allowing you to add multiple records to hasMany
- and hasAndBelongsToMany
-associated models.)
Your specific case is tricky, because you want to save a Control
record, and all of its MainAttribute
records, and all of each MainAttribute
's SubAttribute
records. This isn't possible without some data manipulation in the controller. The way I'd probably tackle this problem is the following.
In the view:
echo $form->create('Control', array('action'=>'add'));
echo $form->input('Control.field_name');
$iLimit = 4;
$jLimit = 2;
for ($k=$i=0;$i<$iLimit;$i++) {
echo $form->input("MainAttribute.{$i}.field_name");
for ($j=0;$j<$jLimit;$j++) {
echo $form->input("SubAttribute.{$k}.ixMainAttribute", array('type'=>'hidden','value'=>$i));
echo $form->input("SubAttribute.{$k}.field_name");
$k++;
}
}
echo $form->end('Submit');
In ControlsController
:
function add()
{
if (! empty($this->data)) {
// Perform data validation separately...
if ( $this->Control->save( $this->data['Control'], false )) {
foreach ( $this->data['MainAttribute'] as $k => $_data ) {
$_subAttributes = Set::extract("/SubAttribute[ixMainAttribute={$k}]", $this->data);
$insert = array(
'MainAttribute' => am( $_data, array('control_id' => $this->Control->id)),
'SubAttribute' => $_subAttributes
);
$this->Control->MainAttribute->saveAll($insert, array('validate'=>false));
}
}
}
}
HTH.