Skip to content

Instantly share code, notes, and snippets.

@davidyell
Last active December 21, 2015 01:39
Show Gist options
  • Save davidyell/6229312 to your computer and use it in GitHub Desktop.
Save davidyell/6229312 to your computer and use it in GitHub Desktop.
AppModel method to fix hasMany multi-select data
<?php
/**
* Transform a set of hasMany multi-select data into a format which can be saved
* using saveAll in the controller
*
* @param array $data
* @param str $fieldToSave
* @param int $deleteId
* @return array
*/
public function massageHasManyForSaveAll($data, $fieldToSave, $deleteId = null) {
foreach ($this->belongsTo as $model => $relationship) {
if ($relationship['foreignKey'] != $fieldToSave) {
$relatedModel = $model;
$relatedModelPrimaryKey = $this->{$model}->primaryKey;
$relatedForeignKey = $relationship['foreignKey'];
}
}
if ($deleteId !== null) {
$this->deleteAll(array(
$this->alias .'.'. $relatedForeignKey => $deleteId
));
}
if (is_array($data[$fieldToSave])) {
foreach ($data[$fieldToSave] as $packageId) {
$return[] = array($fieldToSave => $packageId);
}
return $return;
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment