product_form.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. Session::addAlert("success", __("Product saved successfully."));
  48. Http::redirect($product->getUrl());
  49. }
  50. catch(RuntimeException $e) {
  51. Session::addAlert("danger", $e->getMessage());
  52. }
  53. }
  54. View::include("header");
  55. View::include("product_form", compact("title", "product"));
  56. View::include("footer");