/** * Save Business Unit * * @return void * @author **/ function save_business_unit() { $out = array(); if (!$_POST) { $out['error'] = 'No data'; } elseif (isset($_POST['unitid'])) { $business_unit = new Business_unit(); // Translate groups to single entries $translate = array('keys' => 'key', 'machine_groups' => 'machine_group', 'users' => 'user', 'managers' => 'manager'); $unitid = $_POST['unitid']; // Check if new unit if ($unitid == 'new') { $unitid = $business_unit->get_max_unitid() + 1; } $out['unitid'] = $unitid; // Check if there are changed items if (isset($_POST['iteminfo'])) { $groups = array(); // If sent a '#', no items are in the iteminfo array // proceed with empty groups array if (!in_array('#', $_POST['iteminfo'])) { // Loop through iteminfo foreach ($_POST['iteminfo'] as $entry) { // No key, create new if ($entry['key'] === '') { $mg = new Machine_group(); $newgroup = $mg->get_max_groupid() + 1; // Store name $mg->merge(array('id' => '', 'groupid' => $newgroup, 'property' => 'name', 'value' => $entry['name'])); $mg->save(); // Store GUID key $mg->merge(array('id' => '', 'groupid' => $newgroup, 'property' => 'key', 'value' => get_guid())); $mg->save(); $groups[] = $newgroup; } else { // Add key to list $groups[] = intval($entry['key']); } } } // Set new machine_groups to list $_POST['machine_groups'] = $groups; unset($_POST['iteminfo']); } foreach ($_POST as $property => $val) { // Skip unitid if ($property == 'unitid') { continue; } if (is_scalar($val)) { $business_unit->id = ''; $business_unit->retrieve_one('unitid=? AND property=?', array($unitid, $property)); $business_unit->unitid = $unitid; $business_unit->property = $property; $business_unit->value = $val; $business_unit->save(); $out[$property] = $val; } else { // Check if this is a valid property if (!isset($translate[$property])) { $out['error'][] = 'Illegal property: ' . $property; continue; } // Translate property to db entry $name = $translate[$property]; $business_unit->delete_where('unitid=? AND property=?', array($unitid, $name)); foreach ($val as $entry) { // Empty array placeholder if ($entry === '#') { $out[$property] = array(); continue; } $business_unit->id = ''; $business_unit->unitid = $unitid; $business_unit->property = $name; $business_unit->value = is_numeric($entry) ? 0 + $entry : $entry; $business_unit->save(); $out[$property][] = is_numeric($entry) ? 0 + $entry : $entry; } } } } else { $out['error'] = 'Unitid missing'; } $obj = new View(); $obj->view('json', array('msg' => $out)); }