product_form.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. if(!$product->name) {
  40. throw new RuntimeException(__("Name is required."));
  41. }
  42. if(!$product->type) {
  43. throw new RuntimeException(__("Type is required."));
  44. }
  45. $product->commit();
  46. Session::addAlert("success", __("Product saved successfully."));
  47. Http::redirect($product->getUrl());
  48. }
  49. catch(RuntimeException $e) {
  50. Session::addAlert("danger", $e->getMessage());
  51. }
  52. }
  53. View::include("header");
  54. View::include("product_form", [
  55. "title" => $title,
  56. "product" => $product,
  57. ]);
  58. View::include("footer");