I have a model GenForm
which has a HABTM relationship with another model PdfFile
. I use this to generate a list of checkboxes in my GenForm
index view. In the GenForm
model, I added:
public $hasAndBelongsToMany = array(
'PdfFile' => array(
'className' => 'PdfFile',
'joinTable' => 'gen_forms_x_pdf_files'
)
Here's a fragment from my GenForm
index.ctp
view:
<?php
echo $this->Form->input( 'PdfFile', array('label' => 'Select some PDF files', 'multiple' => 'checkbox') );
echo $this->Form->input( 'first_name' );
echo $this->Form->input( 'last_name' );
?>
In the controller, I have a basic save:
if ($this->request->is('post')) { // form was submitted
$this->GenForm->create();
if ($this->GenForm->save($this->request->data)) {
return $this->redirect(array('action' => 'generate', $this->GenForm->id)); // assemble the PDF for this record
} else {
$this->Session->setFlash(__('Log entry not saved.'));
}
}
Now $this->data
looks something like this when I debug()
it:
array(
'PdfFile' => array(
'PdfFile' => array(
(int) 0 => '1',
(int) 1 => '5'
)
),
'GenForm' => array(
'first_name' => 'xxx',
'last_name' => 'xxx',
'association_id' => '1',
'email' => ''
)
)
Everything works perfectly, but I couldn't validate the checkboxes (at least one must be checked). So, as per this answer, I made some changes.
The index.ctp
view became:
<?php
echo $this->Form->input( 'GenForm.PdfFile', array('label' => 'Select some PDF files', 'multiple' => 'checkbox') );
echo $this->Form->input( 'first_name' );
echo $this->Form->input( 'last_name' );
?>
Here's my validation rule:
public $validate = array(
'PdfFile' => array(
'rule' => array(
'multiple', array('min' => 1)
),
'message' => 'Please select one or more PDFs'
)
)
This is what $this->data
looks like now:
array(
'GenForm' => array(
'PdfFile' => array(
(int) 0 => '1',
(int) 1 => '5'
),
'first_name' => 'xxx',
'last_name' => 'xxx',
'association_id' => '1',
'email' => ''
)
)
Now the checkboxes for PdfFile
validate, but the PdfFile
data isn't saved -- although the other fields for GenForm
are saved correctly to their own table.
Can anyone tell me what I'm missing so that PdfFile
saves automatically and gets validated?