product_form.php 2.1 KB

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