CompanyService.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace App\Livewire;
  3. use Illuminate\Support\Facades\Log;
  4. use Illuminate\Support\Facades\DB;
  5. use Livewire\Attributes\Validate;
  6. use Livewire\Component;
  7. use Livewire\Attributes\Layout;
  8. class CompanyService extends Component
  9. {
  10. public $company;
  11. public $current_company_service = null;
  12. public $company_services = [];
  13. #[Validate('required')]
  14. public $name = '';
  15. public $description = '';
  16. public $enabled = 1;
  17. public $is_edit = false;
  18. public function resetFields(){
  19. $this->name = '';
  20. $this->description = '';
  21. $this->enabled = 1;
  22. }
  23. public function render()
  24. {
  25. $this->company_services = $this->company->services ?? [];
  26. return view('livewire.company_service');
  27. }
  28. public function add()
  29. {
  30. $this->resetFields();
  31. $this->is_edit = true;
  32. $this->current_company_service = null;
  33. }
  34. public function edit($id)
  35. {
  36. $this->resetFields();
  37. $this->is_edit = true;
  38. $this->current_company_service = \App\Models\CompanyService::findOrFail($id);
  39. $this->name = $this->current_company_service->name;
  40. $this->description = $this->current_company_service->description;
  41. $this->enabled = $this->current_company_service->enabled == 1;
  42. }
  43. public function save()
  44. {
  45. $this->validate();
  46. try
  47. {
  48. if ($this->current_company_service == null)
  49. {
  50. \App\Models\CompanyService::create([
  51. 'company_id' => $this->company->id,
  52. 'name' => $this->name,
  53. 'description' => $this->description,
  54. 'enabled' => $this->enabled
  55. ]);
  56. }
  57. else
  58. {
  59. $this->current_company_service->update([
  60. 'name' => $this->name,
  61. 'description' => $this->description,
  62. 'enabled' => $this->enabled ? 1 : 0,
  63. ]);
  64. }
  65. session()->flash('success','Dati salvati con successo');
  66. $this->resetFields();
  67. $this->is_edit = false;
  68. $this->dispatch("update");
  69. } catch (\Exception $ex) {
  70. session()->flash('error','Errore (' . $ex->getMessage() . ')');
  71. }
  72. }
  73. public function cancel()
  74. {
  75. $this->resetFields();
  76. $this->is_edit = false;
  77. $this->current_company_service = null;
  78. $this->dispatch("update");
  79. }
  80. }