location_add.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. $page_title = "Add Location";
  3. $customer = Customer::getForAdmin();
  4. if(!$customer) throw new Exception("You do not have permission to access this page.");
  5. Core::addBreadcrumb("/account", "Account");
  6. Core::addBreadcrumb("/account/locations", "Locations");
  7. Core::addBreadcrumb("/account/locations/add", $page_title);
  8. $location = new Location;
  9. $location->customer_id = $customer->id;
  10. $submit = http::value("submit");
  11. if($submit) {
  12. try {
  13. Core::validateCSRFToken($submit);
  14. $form_exception = new FormException;
  15. $location->name = http::value("name", "trim");
  16. $location->address_1 = http::value("address", "trim");
  17. if(empty($location->name)) $form_exception->addError("Name is required.");
  18. if(empty($location->address_1)) {
  19. $form_exception->addError("Full address is required.");
  20. }
  21. else {
  22. // Geocode the full address
  23. try {
  24. $results = Geolocation::geocode($location->address_1);
  25. $result = $results[0];
  26. foreach($result->address_components as $component) {
  27. $types = $component->types;
  28. if(in_array("postal_code", $types)) $location->postal_code = $component->long_name;
  29. if(in_array("route", $types)) $location->address_1 = $component->long_name;
  30. if(in_array("postal_town", $types)) $location->city = $component->long_name;
  31. if(in_array("administrative_area_level_1", $types)) $location->state = $component->long_name;
  32. if(in_array("country", $types)) $location->country = $component->long_name;
  33. }
  34. $location->latitude = $result->geometry->location->lat;
  35. $location->longitude = $result->geometry->location->lng;
  36. }
  37. catch(Exception $e) {
  38. $form_exception->addError("Failed to get location from full address: " . $e->getMessage());
  39. }
  40. }
  41. if($form_exception->hasErrors()) throw $form_exception;
  42. $success = $location->commit();
  43. if(!$success) throw new Exception("Faileds to add location at this time. Please try again later.");
  44. Core::addAlert("success", "Location added successfully.");
  45. HTTP::redirect("/account/locations/$location->id");
  46. }
  47. catch(FormException $e) {
  48. $e->generateAlerts();
  49. }
  50. catch(Exception $e) {
  51. Core::addAlert("danger", $e->getMessage());
  52. }
  53. }
  54. View::includeOnce("header", compact("page_title"));
  55. View::include("location_add_form", compact("location"));
  56. View::includeOnce("footer");
  57. ?>