product_form.php 1.6 KB

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