0
votes

Scenario

  • I have Provider and Package.
  • A provider can have a number of featured packages.
  • So we need a HABTM between Provider and Package
  • I want to save all the providers featured packages in one shot using the Provider::edit() method

Setup
I have three models.
Provider FeaturedPackage Package

Models

These are setup using the 'HABTM Through', which should not be confused with HABTM. So the relationships are as follows.

Provider hasMany FeaturedPackage
FeaturedPackage belongsTo Provider
Package hasMany FeaturedPackage
FeaturedPackage belongsTo Package

Controller

public function admin_edit($id) {
    if ($this->request->is('post') || $this->request->is('put')) {
        if ($this->Provider->saveAll($this->request->data)) {
// snip

View

echo $this->Form->input('FeaturedPackages', array('type' => 'select', 'multiple' => true, 'options' => $packages));

The issue
I'm not sure how to save multiple variable numbers of hasMany records from one side of the relationship. I know from reading the book that the expected data array should be numerically indexed beneath the model.

However I'm not sure what to name my field to get the data formatted correctly.

I am unable to bake the view as it seems to ignore the hasMany and not even add a field for it.

Field names I've tried
FeaturedPackage
FeaturedPackage.FeaturedPackage
FeaturedPackage.package_id
FeaturedPackage..package_id
FeaturedPackage.[].package_id
FeaturedPackage.package_id][

1

1 Answers

0
votes

I've solved this using a data massage method in my model, which is called from the controller.

This goes through and updates the array submitted from the form to match what is expected by the save.

I blogged my solution, http://jedistirfry.co.uk/blog/2013-08/how-to-create-hasmanythrough-multi-selects/