1
0

product_form.php 2.2 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::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->archived = (int) (bool) $request->int("archived");
  44. $product->commit();
  45. $delete_brochure = $request->int("delete_brochure");
  46. if($delete_brochure && $product->hasBrochure()) {
  47. $product->deleteBrochure();
  48. }
  49. $brochure = $_FILES["brochure"] ?? null;
  50. if($brochure) {
  51. $error = $brochure["error"];
  52. if($error === UPLOAD_ERR_OK) {
  53. Util::createDirectory($_ENV["DIR_ROOT"] . "/files/product");
  54. move_uploaded_file($brochure["tmp_name"], $product->getBrochurePath());
  55. }
  56. else if($error !== UPLOAD_ERR_NO_FILE) {
  57. Session::addAlert("danger", __("Brochure upload failed."));
  58. }
  59. }
  60. Session::addAlert("success", __("Product saved successfully."));
  61. Http::redirect($product->getUpdateUrl());
  62. }
  63. catch(RuntimeException $e) {
  64. Session::addAlert("danger", $e->getMessage());
  65. }
  66. }
  67. $core->addScript("/js/product-form.js");
  68. View::include("header");
  69. View::include("product_form", compact("title", "product"));
  70. View::include("footer");