diff --git a/src/Controller/VehicleController.php b/src/Controller/VehicleController.php index d09d3752..7c388062 100644 --- a/src/Controller/VehicleController.php +++ b/src/Controller/VehicleController.php @@ -286,6 +286,7 @@ class VehicleController extends Controller $batteries = $req->request->get('batteries'); if (!empty($batteries)) { + // TODO: need to move the checking for batteries to a function // need to check if a battery has been removed if (count($current_batteries) > count($batteries)) { @@ -345,6 +346,61 @@ class VehicleController extends Controller } } } + // check if battery was deleted then another one was added + if (count($current_batteries) == count($batteries)) + { + // find deleted battery + foreach ($current_batteries as $cbatt) + { + $cbatt_id = $cbatt->getID(); + if (in_array($cbatt_id, $batteries)) + { + // do nothing, move to next element + continue; + } + else + { + // cbatt_id has been deleted + $del_battery = $em->getRepository(Battery::class)->find($cbatt_id); + + if (!empty($del_battery)) + { + $del_battery->removeVehicle($row); + } + } + } + + // find the battery to add + $cbatt_ids = []; + foreach ($current_batteries as $cbatt) + { + $cbatt_ids = [ + $cbatt->getID(), + ]; + } + + foreach ($batteries as $batt) + { + $batt_id = $batt; + if (in_array($batt_id, $cbatt_ids)) + { + // do nothing since battery already there + continue; + } + else + { + // batt is the new battery + $new_battery = $em->getRepository(Battery::class)->find($batt_id); + + if (!empty($new_battery)) + { + $new_battery->addVehicle($row); + + $em->persist($new_battery); + } + } + } + } } else {