product_form.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php /** @noinspection PhpUnhandledExceptionInspection */
  2. namespace App;
  3. use RuntimeException;
  4. /**
  5. * @var int $id
  6. */
  7. $core = Core::getInstance();
  8. $core->addBreadcrumb("/products", __("Products"));
  9. $user = $core->getUser();
  10. if(isset($id)) {
  11. $product = Product::get($id);
  12. if(!$product) {
  13. throw new RuntimeException(__("Product not found."));
  14. }
  15. $product->dts_updated = Database::dts();
  16. $title = __("Update Product");
  17. }
  18. else {
  19. $product = new Product();
  20. $product->dts_created = Database::dts();
  21. $title = __("Add Product");
  22. }
  23. $core->addBreadcrumb($_SERVER["REQUEST_URI"], $title);
  24. $request = Request::fromPost();
  25. $submit = $request->int("submit");
  26. if($submit) {
  27. try {
  28. $user->requireValidCsrfToken();
  29. $supplier_id = $request->int("supplier_id");
  30. $supplier = Supplier::get($supplier_id);
  31. if(!$supplier) {
  32. throw new RuntimeException(__("Invalid supplier selected."));
  33. }
  34. $product->supplier_id = $supplier_id;
  35. $product->name = $request->string("name");
  36. $product->sku = $request->string("sku");
  37. $product->type = $request->int("type");
  38. $product->price = $request->decimal("price", 2);
  39. $product->url = $request->url("url");
  40. if(!$product->name) {
  41. throw new RuntimeException(__("Name is required."));
  42. }
  43. if(!$product->type) {
  44. throw new RuntimeException(__("Type is required."));
  45. }
  46. $product->commit();
  47. $delete_brochure = $request->int("delete_brochure");
  48. if($delete_brochure && $product->hasBrochure()) {
  49. $product->deleteBrochure();
  50. }
  51. $brochure = $_FILES["brochure"] ?? null;
  52. if($brochure) {
  53. $error = $brochure["error"];
  54. if($error === UPLOAD_ERR_OK) {
  55. Util::createDirectory($_ENV["DIR_ROOT"] . "/files/product");
  56. move_uploaded_file($brochure["tmp_name"], $product->getBrochurePath());
  57. }
  58. else if($error !== UPLOAD_ERR_NO_FILE) {
  59. Session::addAlert("danger", __("Brochure upload failed."));
  60. }
  61. }
  62. Session::addAlert("success", __("Product saved successfully."));
  63. Http::redirect($product->getUrl());
  64. }
  65. catch(RuntimeException $e) {
  66. Session::addAlert("danger", $e->getMessage());
  67. }
  68. }
  69. View::include("header");
  70. View::include("product_form", compact("title", "product"));
  71. View::include("footer");